169. Majority Element

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int majorityElement(int[] nums) {
int majorityElement = 0, votes = 0;
for (int num : nums) {
if (votes == 0) {
majorityElement = num;
}

votes += num == majorityElement ? 1 : -1;
}

return majorityElement;
}
}

References

169. Majority Element
剑指 Offer 39. 数组中出现次数超过一半的数字
面试题 17.10. 主要元素