-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path229 Majority Element II .cpp
52 lines (52 loc) · 1.42 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
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<pair<int, int>> can(2, {0, 0});
for (auto num : nums) {
bool vis = false;
if (!vis) {
for (auto &t : can) {
if (t.first == num) {
vis = true;
t.second++;
break;
}
}
}
if (!vis) {
for (auto &t : can) {
if (!t.second) {
t.first = num;
t.second = 1;
vis = true;
break;
}
}
}
if (!vis) {
if (can[0].second) {
can[0].second--;
}
if (can[1].second) {
can[1].second--;
}
}
}
vector<int> ans;
can[0].second = can[1].second = 0;
for (auto num : nums) {
for (auto &t : can) {
if (t.first == num) {
t.second++;
}
}
}
for (auto &t : can) {
if (t.second > nums.size() / 3) {
ans.push_back(t.first);
}
}
ans.erase(unique(begin(ans), end(ans)), end(ans));
return ans;
}
};