Could anyone help me with my code?


  • 0

    I firstly used a hash map to count the frequency of each element. Then I use a maxHeap to find K frequent elements. I don't know where is the problem of my code. Could anyone tell me why this code is not working?? Thanks.

    public List<Integer> topKFrequent(int[] nums, int k) {
            HashMap<Integer, Integer> map = new HashMap<>();   
            for(int i=0; i< nums.length; i++ ){
                if(!map.containsKey(nums[i])) {
                    map.put(nums[i], 1);
                } else{
                    map.put(nums[i], map.get(nums[i])+1);
                }
            }
            
            PriorityQueue<Map.Entry<Integer,Integer>> pq = 
                new PriorityQueue<Map.Entry<Integer,Integer>>(
                        new Comparator<Map.Entry<Integer,Integer>>(){
                            @Override
                            public int compare(Map.Entry<Integer,Integer> entry1, Map.Entry<Integer,Integer> entry2){
                                return entry2.getValue().compareTo(entry1.getValue());
                            }
                
                        });
            ArrayList<Integer> res = new ArrayList<>();
            
            for(Map.Entry<Integer, Integer> entry : map.entrySet()){
                pq.add(entry);
            }
            int count = 0;
            for(Map.Entry<Integer, Integer> entry : pq){
                if(count < k){
                    res.add(entry.getKey());
                    count++;
                }else{
                    break;
                }
            }
            
            return res;
        }
    

  • 0
    Z

    PriorityQueue cannot grantee the second element is the second least one, when you poll the first one, it will do some work. You need to use pq.poll() to get the least element, in this case the number appears most.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.