-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElements2.java
More file actions
55 lines (47 loc) · 1.43 KB
/
MajorityElements2.java
File metadata and controls
55 lines (47 loc) · 1.43 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
55
import java.util.ArrayList;
import java.util.List;
/**
* Leet code problem, #229: Majority Element II
* Given: Majority element occurs more than [ n / 3 ] times
* https://leetcode.com/problems/majority-element-ii/
*/
public class MajorityElements2 {
public static void main(String[] args) {
int[] arr = { 1, 1, 1, 3, 3, 1, 2, 2, 2, 2 };
System.out.println(majorityElement(arr));
}
public static List<Integer> majorityElement(int[] nums) {
int first = 0, second = 0;
int firstCount = 0, secondCount = 0;
for (int num : nums) {
if (num == first)
firstCount++;
else if (num == second)
secondCount++;
else if (firstCount == 0) {
first = num;
firstCount++;
} else if (secondCount == 0) {
second = num;
secondCount++;
} else {
firstCount--;
secondCount--;
}
}
firstCount = 0;
secondCount = 0;
for (int num : nums) {
if (num == first)
firstCount++;
else if (num == second)
secondCount++;
}
List<Integer> res = new ArrayList<>();
if (firstCount > nums.length / 3)
res.add(first);
if (secondCount > nums.length / 3)
res.add(second);
return res;
}
}