-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path229.cpp
More file actions
54 lines (45 loc) · 1.19 KB
/
229.cpp
File metadata and controls
54 lines (45 loc) · 1.19 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
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> result;
int candidate1, candidate2, count1, count2;
candidate1 = candidate2 = count1 = count2 = 0;
for(int i : nums)
{
if(count1 == 0 && i != candidate2)
{
candidate1 = i;
count1++;
}
else if(i == candidate1)
count1++;
else if(count2 == 0 || i == candidate2)
{
candidate2 = i;
count2++;
}
else
{
count1--;
count2--;
}
}
count1 = count2 = 0;
for(int i : nums)
{
if(i == candidate1)
count1++;
else if(i == candidate2)
count2++;
}
if(count1 > (nums.size() / 3))
result.push_back(candidate1);
if(count2 > (nums.size() / 3))
result.push_back(candidate2);
return result;
}
};