【leetcode每日刷题】347. Top K Frequent Elements

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_38103546/article/details/102763924

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

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

Example 2:

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

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
class Solution {
    public ArrayList<Integer> topKFrequent(int[] nums, int k) {
        ArrayList<Integer> array = new ArrayList<Integer>();
        if(nums.length == 0) return array;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int num: nums){
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        PriorityQueue<Integer> heap = new PriorityQueue<Integer>((n1, n2) -> map.get(n2) - map.get(n1));
        for(int num: map.keySet()){
            heap.add(num);
        }
        while(k-- > 0){
            array.add(heap.poll());
        }
        return array;
    }
}

使用优先队列对map中的值进行排序,然后获得钱k个元素。

猜你喜欢

转载自blog.csdn.net/m0_38103546/article/details/102763924