-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0229.cpp
More file actions
30 lines (29 loc) · 747 Bytes
/
Copy path0229.cpp
File metadata and controls
30 lines (29 loc) · 747 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
class Solution {
public:
vector<int> majorityElement(vector<int> &nums) {
int a = -1, b = -1, ca = 0, cb = 0;
for (const int n : nums) {
if (n == a)
ca++;
else if (b == n)
cb++;
else if (!ca)
a = n, ca = 1;
else if (!cb)
b = n, cb = 1;
else
ca--, cb--;
}
ca = cb = 0;
for (const int n : nums) {
if (n == a)
ca++;
else if (n == b)
cb++;
}
vector<int> res;
if (ca > nums.size() / 3) res.push_back(a);
if (cb > nums.size() / 3) res.push_back(b);
return res;
}
};