-
Notifications
You must be signed in to change notification settings - Fork 0
/
Majority element
37 lines (35 loc) · 1.02 KB
/
Majority element
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
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res=new ArrayList<>();
if(nums.length==0) return res;
int c1=0, c2=0, maj_ind1=0, maj_ind2=0, req=nums.length/3;
for(int i=0; i<nums.length; i++){
if(nums[maj_ind1]==nums[i]) c1++;
else if(nums[maj_ind2]==nums[i]) c2++;
else if(c1==0){
maj_ind1=i;
c1=1;
}
else if(c2==0){
maj_ind2=i;
c2=1;
}
else {
c1--;
c2--;
}
}
int max1=nums[maj_ind1];
int max2=nums[maj_ind2];
c1=0;
c2=0;
//counting occurences to check whether its freq greater than n/3
for(int i=0; i<nums.length; i++){
if(nums[i]==max1) c1++;
else if(nums[i]==max2) c2++;
}
if(c1>req) res.add(max1);
if(c2>req) res.add(max2);
return res;
}
}