题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
// 第一个打擂台的人
int voted = 1;
int result = array[0];
for (int i = 1; i < array.length; i++) {
if(array[i] == result) {// 如果是同盟战力值++
voted++;
}else{
// 如果不是同盟战力值--
voted--;
if(voted==0){ // 战力值耗尽退出擂台,重置擂主
voted=1;
result = array[i];
}
}
}
// 最终在台上的说明战力值比较屌的人
return result;
}
}
解题思想:联想打擂台,站在最后的就是要找的次数最多的。
#算法##算法笔记#