-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_229_MajorityElementII.cpp
76 lines (66 loc) · 1.75 KB
/
LC_229_MajorityElementII.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
229. Majority Element II
https://leetcode.com/problems/majority-element-ii/
*/
class Solution {
public:
//Using Extra Space O(n)
vector<int> majorityElement1(vector<int>& nums) {
vector<int> ans;
unordered_map<int,int> count;
int th = nums.size()/3;
for(int i=0; i<nums.size(); i++)
{
count[nums[i]]++;
if(count[nums[i]]>th)
{
ans.push_back(nums[i]);
count[nums[i]]=-1;
}
}
for(auto x: count)
cout<<x.first<<" "<<x.second<<endl;
return ans;
}//end
vector<int> majorityElement(vector<int>& nums) {
vector<int> ans;
//for n/3 there are two candidate
int cand1 = -1, cand2 = -1;
int cnt1=0, cnt2=0;
for(int i=0; i<nums.size(); i++)
{
if(cand1 == nums[i])
cnt1++;
else if(cand2 == nums[i])
cnt2++;
else
{
if(cnt1==0)
{
cand1=nums[i];
cnt1=1;
}
else if(cnt2==0)
{
cand2 = nums[i];
cnt2=1;
}
else
{
cnt1--;
cnt2--;
}
}
}
cnt1=0;
cnt2=0;
for(auto x: nums)
{
if(cand1 == x)cnt1++;
else if(cand2 == x)cnt2++;
}
if(cnt1 > nums.size()/3) ans.push_back(cand1);
if(cnt2 > nums.size()/3) ans.push_back(cand2);
return ans;
}//end
};