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