-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode229.java
More file actions
49 lines (44 loc) · 1.53 KB
/
LeetCode229.java
File metadata and controls
49 lines (44 loc) · 1.53 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
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Arrays;
public class LeetCode229 {
public static void main(String[] args) {
// 输入:nums = [3,2,3]
// 输出:[3]
System.out.println(Arrays.toString(new Solution229().majorityElement(new int[] { 3, 2, 3 }).toArray()));
// 输入:nums = [1]
// 输出:[1]
System.out.println(Arrays.toString(new Solution229().majorityElement(new int[] { 1 }).toArray()));
// 输入:nums = [1,2]
// 输出:[1,2]
System.out.println(Arrays.toString(new Solution229().majorityElement(new int[] { 1, 2 }).toArray()));
}
}
class Solution229 {
public List<Integer> majorityElement(int[] nums) {
int length = nums.length;
int onethird = length / 3;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
if (map.get(nums[i]) + length - i > onethird) {
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.remove(nums[i]);
}
} else {
if (length - i > onethird) {
map.put(nums[i], 1);
}
}
}
List<Integer> result = new ArrayList<>();
for (Integer item : map.keySet()) {
if (map.get(item) > onethird) {
result.add(item);
}
}
return result;
}
}