-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMajority Element II.java
32 lines (32 loc) · 1000 Bytes
/
Majority Element II.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
class Solution {
public List<Integer> majorityElement(int[] nums) {
int val1 = nums[0], val2 = nums[0], cnt1 = 1, cnt2 = 0;
for(int i = 1; i < nums.length; i++){
if(val1 == nums[i]){
cnt1++;
} else if(val2 == nums[i]){
cnt2++;
} else{
if(cnt1 == 0){
val1 = nums[i];
cnt1++;
} else if(cnt2 == 0){
val2 = nums[i];
cnt2++;
} else{
cnt1--;
cnt2--;
}
}
}
int check1 = 0, check2 = 0;
for(int i = 0; i < nums.length; i++){
if(val1 == nums[i])check1++;
else if(val2 == nums[i])check2++;
}
List<Integer> ans = new ArrayList<>();
if(check1 > nums.length / 3) ans.add(val1);
if(check2 > nums.length / 3) ans.add(val2);
return ans;
}
}