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 Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res=new ArrayList<Integer>();
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
int n=nums.length;
int time=n/3;
for(int i=0;i<n;i++){
if(map.containsKey(nums[i])){
int a=map.get(nums[i]);
a++;
if(a>time&&!res.contains(nums[i])){
res.add(nums[i]);
map.put(nums[i], 0);
}else{
map.put(nums[i], a);
}
}else{
if(1>time){
res.add(nums[i]);
}
map.put(nums[i], 1);
}
}
return res;
}
}