-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path229. Majority Element II.cpp
67 lines (53 loc) · 1.63 KB
/
229. 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// -----Approach 1: using map ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/majority-element-ii/
Time: 20 ms (Beats 40.12%), Space: 16 MB (Beats 16.83%)
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
map<int,int> mpp;
for(auto i: nums) mpp[i]++;
vector<int> ans;
for(auto it: mpp)
if( it.second > nums.size()/3 )
ans.push_back(it.first);
return ans;
}
};
// -----Approach 2: using Boyer Moore Voting Algorithm ------------------------------------------------------------
/*
Problem Link: https://leetcode.com/problems/majority-element-ii/
Time: 16 ms (Beats 62.49%), Space: 16 MB (Beats 56.76%)
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int cnt1= 0, cnt2= 0, num1= -1, num2= -1;
for(auto i: nums){
if(num1 == i) cnt1++;
else if(num2 == i) cnt2++;
else if(cnt1 == 0){
num1= i;
cnt1++;
}
else if(cnt2 == 0){
num2= i;
cnt2++;
}
else{
cnt1--;
cnt2--;
}
}
cnt1= 0, cnt2= 0;
for(auto i: nums){
if(i == num1) cnt1++;
else if(i == num2) cnt2++;
}
vector<int> v;
if(cnt1 > nums.size()/3) v.push_back(num1);
if(cnt2 > nums.size()/3) v.push_back(num2);
return v;
}
};