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.
public class Solution229 {
public List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length;i++) {
int cnt = 0;
if(map.containsKey(nums[i])) {
cnt = map.get(nums[i]).intValue()+1;
} else {
cnt=1;
}
map.put(nums[i],cnt);
}
int n = nums.length/3;
for (Integer key:map.keySet()) {
int cnt = map.get(key);
if(cnt > n) {
result.add(key);
}
}
return result;
}
public static void main(String[] args) {
}
}