-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmajorityElement2.cpp
More file actions
50 lines (44 loc) · 1.2 KB
/
Copy pathmajorityElement2.cpp
File metadata and controls
50 lines (44 loc) · 1.2 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
48
49
50
#include<bits/stdc++.h>
using namespace std;
vector<int> majorityElement(vector<int>& nums) {
vector<int> X;
int majority1=INT_MAX, majority2=INT_MAX ;
int count1 = 0, count2 = 0;
for(int i : nums){
if(i == majority1)
++count1;
else if(i == majority2)
++count2;
else if(count1 == 0) {
majority1 = i;
count1=1;
} else if(count2 == 0) {
majority2 = i;
count2=1;
} else{
--count1;
--count2;
}
}
count1 = 0, count2 =0;
for(int i: nums){
if(i==majority1)
count1++;
else if(i==majority2)
count2++;
}
if(count1 > (nums.size()/3))
X.push_back(majority1);
if(count2 > (nums.size()/3))
X.push_back(majority2);
return X;
}
int main(){
vector<int> arr= {1,1,1,2,3,3,2,2};
vector<int> res;
res=majorityElement(arr);
for(auto i:res){
cout<<i<<" ";
}
return 0;
}