-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathMajorityElementII.cpp
64 lines (49 loc) · 1.38 KB
/
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
/*
Source: https://leetcode.com/problems/majority-element-ii/
Time: O(n), where n is the size of the given vector(nums)
Space: O(1), in-place
*/
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int firstCandidate = nums[0];
int firstCandidateCount = 1;
int secondCandidate = nums[0];
int secondCandidateCount = 0;
int size = nums.size();
for(int i = 1; i < size; ++i) {
if(nums[i] == firstCandidate) {
++firstCandidateCount;
} else if(nums[i] == secondCandidate) {
++secondCandidateCount;
} else if(firstCandidateCount == 0) {
firstCandidate = nums[i];
firstCandidateCount = 1;
} else if(secondCandidateCount == 0) {
secondCandidate = nums[i];
secondCandidateCount = 1;
} else {
--firstCandidateCount;
--secondCandidateCount;
}
}
firstCandidateCount = 0;
secondCandidateCount = 0;
for(int num : nums) {
if(num == firstCandidate) {
++firstCandidateCount;
} else if(num == secondCandidate) {
++secondCandidateCount;
}
}
vector<int> candidates;
int nByThree = size / 3;
if(firstCandidateCount > nByThree) {
candidates.push_back(firstCandidate);
}
if(secondCandidateCount > nByThree) {
candidates.push_back(secondCandidate);
}
return candidates;
}
};