题解 | #数组中出现次数超过一半的数字#
数组中出现次数超过一半的数字
https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163
O(n) 时间复杂度,题目说了肯定有解
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int res = 0, vote = 0;
for (int i = 0; i < array.length; i ++ ) {
if (vote == 0) {
res = array[i];
vote ++ ;
} else if (res == array[i]) {
vote ++ ;
} else if (res != array[i]) {
vote -- ;
}
}
return res;
}
}

查看1道真题和解析
