-
Notifications
You must be signed in to change notification settings - Fork 4
/
MajorityElementII.java
34 lines (31 loc) · 976 Bytes
/
MajorityElementII.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
package com.dbc;
import java.util.ArrayList;
import java.util.List;
public class MajorityElementII {
public List<Integer> majorityElement(int[] nums) {
int num1 = 0, num2 = 0, vote1 = 0, vote2 = 0;
for (int j : nums) {
if (vote1 > 0 && num1 == j) vote1++;
else if (vote2 > 0 && num2 == j) vote2++;
else if (vote1 == 0) {
num1 = j;
vote1++;
} else if (vote2 == 0) {
num2 = j;
vote2++;
} else {
vote1--;
vote2--;
}
}
int count1 = 0, count2 = 0;
for (int num : nums) {
if (vote1 > 0 && num == num1) count1++;
if (vote2 > 0 && num == num2) count2++;
}
List<Integer> res = new ArrayList<>();
if (count1 > nums.length / 3) res.add(num1);
if (count2 > nums.length / 3) res.add(num2);
return res;
}
}