7月27日:前K个高频元素

题目如下:

7月27日:前K个高频元素

经过这么多天的刷题以后,看到这道题目还是有思路的,毕竟遇到数组中求一个数的频率问题,首先肯定能想到用HashMap来统计频率。而要求前K问题很明显是得用堆排序。

虽然HashMap容易写,但将它和堆结合以前没写过,所以哇,还是没有写出来(主要还是堆排序不太会写);

可是在java中它有一个优先队列就实现了小顶堆的功能。

代码如下:

class Solution {

    public int[] topKFrequent(int[] nums, int k) {

        if(nums.length==0) return null;

        HashMap<Integer,Integer> map = new HashMap<>();

        for(int i=0;i<nums.length;i++){

            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);

        }

        PriorityQueue<Integer> heap = new PriorityQueue<Integer>((n1,n2)->map.get(n1)-map.get(n2));

        for(int key:map.keySet()){

            heap.add(key);

            if(heap.size()>k){

                heap.poll();

            }

        }

        ArrayList<Integer> top_k = new ArrayList<>();

        int[] result = new int[k];

        int i =k-1;

        while (!heap.isEmpty()){

            result[i] = heap.poll();

            i--;

        }

        return result;

    }

}