-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path229_majorityElement.java
More file actions
47 lines (44 loc) · 1.1 KB
/
229_majorityElement.java
File metadata and controls
47 lines (44 loc) · 1.1 KB
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
40
41
42
43
44
45
46
47
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums.length == 0)
return res;
int cand1 = nums[0],cand2 = nums[0];
int count1 = 0,count2= 0;
for(int num:nums){
if(num == cand1){
count1++;
continue;
}
if(num == cand2){
count2++;
continue;
}
if(count1 == 0){
cand1 = num;
count1++;
continue;
}
if(count2 == 0){
cand2 = num;
count2++;
continue;
}
count1--;
count2--;
}
count1 = 0;
count2 = 0;
for(int num:nums){
if(num == cand1)
count1++;
if(num == cand2)
count2++;
}
if(count1>nums.length/3)
res.add(cand1);
if(cand2!=cand1&&count2>nums.length/3)
res.add(cand2);
return res;
}
}