在 Java 中从 hashmap 中删除键时出现 java.lang.NullPointerException

问题描述 投票:0回答:1

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;
}

}

想要从哈希图中删除键以在迭代时获取下一个最大元素

java nullpointerexception hashmap iterator integer
1个回答
0
投票

将这两行移到循环内。您需要在每次循环迭代后重置这两个值。

for (int i=0; i<k; i++){
    currentGreatestValue = 0;
    Iterator hmIterator = hm.entrySet().iterator();
© www.soinside.com 2019 - 2024. All rights reserved.