解法1
多数元素重复次数大于一半,多数投票,最终ans至少多出现一次
class Solution {
public int majorityElement(int[] nums) {
int ans = nums[0], cnt = 1;
for(int i = 1; i < nums.length; i++) {
if (ans == nums[i]) {
cnt++;
} else {
cnt--;
if (cnt < 0) {
ans = nums[i];
cnt = 1;
}
}
}
return ans;
}
}