-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMajorityElement2.java
More file actions
86 lines (72 loc) · 2.23 KB
/
MajorityElement2.java
File metadata and controls
86 lines (72 loc) · 2.23 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Description: https://leetcode.com/problems/majority-element-ii
* Difficulty: Medium
*/
public class MajorityElement2 {
/**
* Time complexity: O(n)
* Space complexity: O(1)
*/
public List<Integer> majorityElementViaMooreAlgo(int[] nums) {
int count1 = 0;
int count2 = 0;
// there can only be 2 elements that appear more than n/3 times
int candidate1 = nums[0];
int candidate2 = nums[0];
for (int num : nums) {
if (candidate1 == num) {
count1++;
} else if (candidate2 == num) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1++;
} else if (count2 == 0) {
candidate2 = num;
count2++;
} else {
count1--;
count2--;
}
}
// second pass to check, if candidates really appear more than n/3 times
return checkCandidatesFrequency(nums, candidate1, candidate2);
}
private List<Integer> checkCandidatesFrequency(int[] nums, int candidate1, int candidate2) {
int count1 = 0;
int count2 = 0;
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
}
}
int n = nums.length / 3;
List<Integer> result = new ArrayList<>();
if (count1 > n) result.add(candidate1);
if (count2 > n) result.add(candidate2);
return result;
}
/**
* Time complexity: O(n)
* Space complexity: O(m)
*/
public List<Integer> majorityElementViaMap(int[] nums) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.merge(num, 1, Integer::sum);
}
List<Integer> result = new ArrayList<>();
int n = nums.length / 3;
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
if (entry.getValue() > n) result.add(entry.getKey());
}
return result;
}
}