-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathMajority_Element_II.cpp
More file actions
34 lines (34 loc) · 904 Bytes
/
Majority_Element_II.cpp
File metadata and controls
34 lines (34 loc) · 904 Bytes
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
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int countA = 0;
int countB = 0;
int A, B;
int n = nums.size();
for(int i = 0; i < n; ++i) {
if((countA == 0 and B != nums[i]) or A == nums[i]) {
++countA;
A = nums[i];
} else if(countB == 0 or B == nums[i]) {
++countB;
B = nums[i];
} else {
--countA;
--countB;
}
}
countA = countB = 0;
for(int i = 0; i < n; ++i) {
countA += (A == nums[i]);
countB += (B == nums[i]);
}
vector<int> result;
if(countA > floor(n / 3)) {
result.push_back(A);
}
if(countB > floor(n / 3)) {
result.push_back(B);
}
return result;
}
};