-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority_element2.cpp
More file actions
55 lines (46 loc) · 1.21 KB
/
Copy pathmajority_element2.cpp
File metadata and controls
55 lines (46 loc) · 1.21 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
51
52
53
54
55
// Problem Link : https://leetcode.com/problems/majority-element-ii/description/
vector<int> majorityElement(vector<int>& nums) {
int n = nums.size() ;
int count1= 0 ;
int count2 = 0 ;
int element1= INT_MIN ;
int element2 = INT_MIN ;
for(auto i : nums){
if(count1==0 && i!=element2){
count1++ ;
element1=i ;
}
else if(count2==0 && i!=element1){
count2++ ;
element2= i ;
}
else if(i==element1){
count1++ ;
}
else if(i==element2){
count2++ ;
}
else {
count1-- ;
count2-- ;
}
}
vector<int>ans ;
count1= 0 ;
count2=0 ;
for(auto i :nums){
if(i==element1){
count1++ ;
}
if(i==element2){
count2++ ;
}
}
if(count1>=(int)(n/3)+1){
ans.push_back(element1) ;
}
if(count2>=(int)(n/3)+1){
ans.push_back(element2) ;
}
return ans ;
}