347. 前 K 个高频元素 - 力扣(LeetCode)

# Description

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:

Input: nums = [1], k = 1
Output: [1]

Constraints:

1 <= nums.length <= 105
k is in the range [1, the number of unique elements in the array].
It is guaranteed that the answer is unique.

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

# Code

用 min heap 的方法
time complexity O (n log n)

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
    
        Map<Integer, Integer> hm = new HashMap<>();
        for (int num: nums) {
            hm.put(num, hm.getOrDefault(num, 0) + 1);
        }
   
        Queue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>(){
            public int compare(int[] x, int[] y) {
                return x[1] - y[1];
            }
        });
        for (int key : hm.keySet()) {
            queue.offer(new int[]{key, hm.get(key)});
            if (queue.size() > k) {
                queue.poll();
            }
        }
        int[] res = new int[k];
 
        for(int i = k - 1; i >= 0; i--){
          res[i] = queue.poll()[0];
        }
        return res;
    }
}

Reference:
O (n) 的桶排解法
347. 前 K 个高频元素 - 前 K 个高频元素 - 力扣(LeetCode)