Sword refers to offer 39. Numbers that appear more than half the number of times in the array
Title description
Problem-solving ideas
Moore vote
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;
}
}