forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_229.java
37 lines (31 loc) · 1.06 KB
/
_229.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Hint:
How many majority elements could it possibly have?
Do you have a better hint? Suggest it!
*/
public class _229 {
public List<Integer> majorityElement(int[] nums) {
Map<Integer, Integer> counterMap = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (counterMap.containsKey(nums[i])) {
counterMap.put(nums[i], counterMap.get(nums[i]) + 1);
} else {
counterMap.put(nums[i], 1);
}
}
int size = nums.length;
List<Integer> result = new ArrayList<Integer>();
for (Integer i : counterMap.keySet()) {
if (counterMap.get(i) > size / 3) {
result.add(i);
}
}
return result;
}
}