229. Majority Element 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.

解法1:

Moore Voting 算法的延伸。 和Majority Element I类似,这里用两个变量来维护当前出现次数较大的数字。
对于第二个元素n2初始化为0是没关系的,因为他的计数器初始化为0。如果有数字和他一样的话计数器再加1。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if (nums == null || nums.length == 0) {
return res;
}
int n1 = nums[0], n2 = 0, c1 = 0, c2 = 0;
for (int num : nums) {
if (num == n1) {
c1++;
} else if (num == n2) {
c2++;
} else if (c1 == 0) {
n1 = num;
c1 = 1;
} else if (c2 == 0) {
n2 = num;
c2 = 1;
} else {
c1--;
c2--;
}
}
c1 = 0;
c2 = 0;
for (int num : nums) {
if (num == n1) {
c1++;
} else if (num == n2) {
c2++;
}
}
if (c1 > nums.length / 3) {
res.add(n1);
}
if (c2 > nums.length / 3) {
res.add(n2);
}
return res;
}
}