-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
55 lines (52 loc) · 1.35 KB
/
main.cpp
File metadata and controls
55 lines (52 loc) · 1.35 KB
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 摩尔投票算法
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int candidate1, candidate2;
int count1 = 0, count2 = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(nums[i] == candidate1) count1++;
else if(nums[i] == candidate2) count2++;
else{
if(count1 && count2) {
count1--;
count2--;
}
else if(count1)
{
candidate2 = nums[i];
count2 = 1;
}
else
{
candidate1 = nums[i];
count1 = 1;
}
}
}
vector<int> candidate;
if(count1 > 0) candidate.push_back(candidate1);
if(count2 > 0) candidate.push_back(candidate2);
vector<int> res;
for(int i = 0; i < candidate.size(); ++i)
{
int count = 0;
for(int j = 0; j < nums.size(); ++j)
{
if(candidate[i] == nums[j])
count++;
}
if(count > nums.size()/3) res.push_back(candidate[i]);
}
return res;
}
};
int main()
{
return 0;
}