Java LeetCode 347. Top K high-frequency elements

Given a non-empty integer array, return the elements with the k highest occurrence frequency.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]

First record the number of occurrences of each element in the array in the hash, then construct a priority queue through the small top pile, put the small one on the top of the pile, and delete the top of the pile every time it is compared with the top of the pile. Then put this number in.

class Solution {
    
    
    public int[] topKFrequent(int[] nums, int k) {
    
    
        Map<Integer,Integer> hash = new HashMap();

        for(int i:nums){
    
    
            if(hash.containsKey(i)){
    
    
                hash.put(i,hash.get(i)+1);
            }
            else{
    
    
                hash.put(i,1);
            }
        }

        PriorityQueue<Integer> que = new PriorityQueue(k,(v1,v2)->{
    
    
            return hash.get(v1)-hash.get(v2);
        }
            
        );

        for(int key:hash.keySet()){
    
    
            if(que.size()<k){
    
    
                que.offer(key);
            }
            else{
    
    
                if(hash.get(key)>hash.get(que.peek())){
    
    
                    que.poll();
                    que.offer(key);
                }
            }
            
        }

        int list[] = new int[k];

        for(int i=0;i<k;i++){
    
    
            list[i]=que.poll();
        }

        return list;
    }
}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/110357105