publicclassSolution {/**
* @param nums: A list of integers
* @param k: the majority number occurs more than 1/k of the size of the array.
* @return: The majority number
* O(n) time and O(k) extra space
*/publicintmajorityNumber(ArrayList<Integer> nums, int k) {
/**
* 使用HashMap,遍历nums 存k个entry = (value, count).
* 若已经有k个不同的元素在map中,新value抵销所有entry的count一次并删除count为零的entry.
* (因此count并不是每个value的真实数目)
* 遍历一遍后map中所有key都可能是majority,再遍历nums,找出真实count最大
*/
HashMap<Integer, Integer> map = new HashMap<>(); //O(k) spacefor (int i = 0; i < nums.size() ; i++) { //O(n)timeint currVal = nums.get(i);
if (map.containsKey(currVal)) {
map.put(currVal, map.get(currVal) + 1);
} elseif (map.size() < k) {
map.put(currVal, 1);
} else { //remove count-0 keys
ArrayList<Integer> keys = new ArrayList<Integer>(map.keySet());
for (Integer key : keys) {
map.put(key, map.get(key) - 1);
if (map.get(key) == 0) {
map.remove(key);
}
}
} //end else
}// end for, all the keys in map can be candidate int ans = 0;
int count = 0;
for (Integer key : nums) {
if (map.containsKey(key)) {
if (map.get(key) > count) {
ans = key;
count = map.get(key);
}
}
}
return ans;
}
}