-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMajorityElement2.java
More file actions
36 lines (32 loc) · 862 Bytes
/
MajorityElement2.java
File metadata and controls
36 lines (32 loc) · 862 Bytes
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
import java.util.*;
public class MajorityElement2 {
public List<Integer> majorityElement(int[] nums) {
int n1 = 0, n2 = 0;
int c1 = 0, c2 = 0;
for (int num : nums) {
if (num == n1) {
c1++;
} else if (num == n2) {
c2++;
} else if (c1 == 0) {
n1 = num;
c1++;
} else if (c2 == 0) {
n2 = num;
c2++;
} else {
c1--;
c2--;
}
}
List<Integer> res = new ArrayList<>();
c1 = 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;
}
}