-
Notifications
You must be signed in to change notification settings - Fork 0
/
229. Majority Element II.cpp
60 lines (59 loc) · 2.72 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
53
54
55
56
57
58
59
60
/*
Problem Description:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> results;
int num1=INT_MAX,num2=INT_MAX;
int count1=0,count2=0;
for(auto num:nums)
{
if(num==num1)
{
count1++;
}
else if(num==num2)
{
count2++;
}
else if(count1==0)
{
num1=num;
count1++;
}
else if(count2==0)
{
num2=num;
count2++;
}
else
{
count1--;
count2--;
}
}
count1=0;count2=0;
for(auto num:nums)
{
if(num==num1)
{
count1++;
}
else if(num==num2)
{
count2++;
}
}
if(count1>nums.size()/3)
{
results.push_back(num1);
}
if(count2>nums.size()/3)
{
results.push_back(num2);
}
return results;
}
};