LeetCode: MajorityElement II

LeetCode: MajorityElement II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

The algorithm should run in linear time and in O(1) space.

Solution:

要点就是摩尔投票法: https://www.zhihu.com/question/49973163

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MajorityElementII {
public List<Integer> majorityElement(int[] nums) {
int a, b, ca, cb;
a = b = ca = cb = 0;
for (int n : nums) {
if(n == a) ca++;
else if (n == b) cb++;
else if(ca == 0) {a = n;ca++;}
else if(cb == 0) {b = n;cb++;}
else {ca--;cb--;}
}

ca = cb = 0;
for (int n : nums) {
if (n == a) ca++;
else if (n == b) cb++;
}
List<Integer> result = new ArrayList<>();
if (ca > nums.length / 3) result.add(a);
if (cb > nums.length / 3) result.add(b);
return result;
}
}