剑指offer 39. 数组中出现次数超过一半的数字
题目描述
解题思路
摩尔投票
class Solution {
public int majorityElement(int[] nums) {
int mostNum = 0, votes = 0;
for (int num : nums) {
//票数为0,则选取当前的新元素为众数
if (votes == 0) {
mostNum = num;
votes++;
} else {
//如果当前元素等于众数,则票数加1,否则减1
votes += (num == mostNum) ? 1 : -1;
}
}
return mostNum;
}
}