forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path229_majorityElement.java
39 lines (36 loc) · 1.17 KB
/
229_majorityElement.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
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<Integer>();
if(nums == null || nums.length == 0) return res;
int first = nums[0];
int second = nums[0];
int count1 = 0;
int count2 = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == first){
count1++;
} else if(nums[i] == second){
count2++;
} else if(count1 == 0){
first = nums[i];
count1++;
} else if(count2 == 0){
second = nums[i];
count2++;
} else{
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == first) count1++;
//here is else if!!! to get rid of both first and second are the same scenario
else if(nums[i] == second) count2++;
}
if(count1 > nums.length/3) res.add(first);
if(count2 > nums.length/3) res.add(second);
return res;
}
}