https://leetcode.com/problems/top-k-frequent-elements/
问题发生在线路:
hm.remove(currentGreatestValue);
类解决方案{ 公共 int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i=0; i<nums.length; i++){
if (!hm.containsKey(nums[i])){
hm.put(nums[i], 1);
} else {
int occurances = hm.get(nums[i]);
occurances = occurances + 1;
hm.put(nums[i], occurances);
}
}
int mostOccuredValues[] = new int[k];
Iterator hmIterator = hm.entrySet().iterator();
int currentGreatestValue=0;
int currentValue;
int nextGreatestIndex=0;
for (int i=0; i<k; i++){
while (hmIterator.hasNext()) {
Map.Entry mapElement = (Map.Entry)hmIterator.next();
currentValue = (int)mapElement.getKey();
if (currentValue>currentGreatestValue){
currentGreatestValue = currentValue;
}
}
mostOccuredValues[nextGreatestIndex] = hm.get(currentGreatestValue);
nextGreatestIndex = nextGreatestIndex + 1;
hm.remove(currentGreatestValue);
}
return mostOccuredValues;
}
}
想要从哈希图中删除键以在迭代时获取下一个最大元素
将这两行移到循环内。您需要在每次循环迭代后重置这两个值。
for (int i=0; i<k; i++){
currentGreatestValue = 0;
Iterator hmIterator = hm.entrySet().iterator();