Skip to content

Commit 1432ca0

Browse files
authored
Create Solution.java
1 parent ab7d36a commit 1432ca0

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public List<Integer> majorityElement(int[] nums) {
3+
int[] candidate = new int[2];
4+
int[] cnt = new int[2];
5+
for (int num : nums) {
6+
if (num == candidate[0]) {
7+
++cnt[0];
8+
} else if (num == candidate[1]) {
9+
++cnt[1];
10+
} else if (cnt[0] == 0) {
11+
candidate[0] = num;
12+
cnt[0] = 1;
13+
} else if (cnt[1] == 0) {
14+
candidate[1] = num;
15+
cnt[1] = 1;
16+
} else {
17+
--cnt[0];
18+
--cnt[1];
19+
}
20+
}
21+
Arrays.fill(cnt, 0);
22+
for (int num : nums) {
23+
if (num == candidate[0]) {
24+
++cnt[0];
25+
} else if (num == candidate[1]) {
26+
++cnt[1];
27+
}
28+
}
29+
List<Integer> res = new ArrayList<>();
30+
if (cnt[0] > nums.length / 3) {
31+
res.add(candidate[0]);
32+
}
33+
if (cnt[1] > nums.length / 3) {
34+
res.add(candidate[1]);
35+
}
36+
return res;
37+
}
38+
}

0 commit comments

Comments
 (0)