-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path229. Majority Element II
More file actions
36 lines (32 loc) · 989 Bytes
/
229. Majority Element II
File metadata and controls
36 lines (32 loc) · 989 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
class Solution {
public List<Integer> majorityElement(int[] nums) {
int candidate1 = 0, candidate2 = 1;
int count1 = 0, count2 = 0;
for (int num : nums) {
if (candidate1 == num) {
count1++;
} else if (candidate2 == num) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1++;
} else if (count2 == 0) {
candidate2 = num;
count2++;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
List<Integer> result = new ArrayList<>();
for (int num : nums) {
if (candidate1 == num) count1++;
if (candidate2 == num) count2++;
}
if (count1 > nums.length / 3) result.add(candidate1);
if (count2 > nums.length / 3) result.add(candidate2);
return result;
}
}