-
Notifications
You must be signed in to change notification settings - Fork 0
/
0229_Majority_Element_II.cpp
49 lines (48 loc) · 1.04 KB
/
0229_Majority_Element_II.cpp
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
48
49
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int n = nums.size();
int count1=0;
int maj1=0;
int count2=0;
int maj2=0;
for(int i=0; i<n; i++){
if(nums[i]==maj1){
count1++;
}
else if(nums[i]==maj2){
count2++;
}
else if(count1==0){
maj1=nums[i];
count1=1;
}
else if(count2==0){
maj2=nums[i];
count2=1;
}
else{
count1--;
count2--;
}
}
vector<int> res;
int f=0;
int r=0;
for(int &ans:nums){
if(ans==maj1){
f++;
}
else if(ans==maj2){
r++;
}
}
if(f>floor(n/3)){
res.push_back(maj1);
}
if(r>floor(n/3)){
res.push_back(maj2);
}
return res;
}
};