-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajorityElementII.cpp
More file actions
38 lines (37 loc) · 922 Bytes
/
majorityElementII.cpp
File metadata and controls
38 lines (37 loc) · 922 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
35
36
37
38
// Source: https://leetcode.com/problems/majority-element-ii/
// Author: Miao Zhang
// Date: 2021-01-28
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int n1 = 0;
int c1 = 0;
int n2 = 1;
int c2 = 0;
for (auto num: nums) {
if (num == n1) c1++;
else if (num == n2) c2++;
else if (c1 == 0) {
n1 = num;
c1++;
} else if (c2 == 0) {
n2 = num;
c2++;
} else {
c1--;
c2--;
}
}
c1 = 0;
c2 = 0;
for (auto num: nums) {
if (num == n1) c1++;
if (num == n2) c2++;
}
vector<int> res;
int n = nums.size() / 3;
if (c1 > n) res.push_back(n1);
if (c2 > n) res.push_back(n2);
return res;
}
};