347. 前K个高频元素

优先队列+Map

import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;

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

        /**
         * 先将数组所有元素的次数存进map中
         */
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }

        /**
         * 使用优先队列的最小堆
         * 按照map的value大小进行存储
         */
        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return map.get(o1) - map.get(o2);
            }
        });

        /**
         * 当优先队列元素个数小于k时,直接存入
         * 否则,挨个和堆顶元素(value最小)比较,如果比他大就替换
         */
        for (Integer key : map.keySet()){

            if (pq.size() < k){
                pq.add(key);
            }
            else {

                if (map.get(key) > map.get(pq.peek())){

                    pq.poll();
                    pq.add(key);
                }
            }
        }

        int[] res = new int[k];

        for (int i = 0; i < res.length; i++) {
            res[i] = pq.poll();
        }

        return res;
    }
}

/**
 * 时间复杂度 O(nlogk)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/top-k-frequent-elements/

posted @ 2021-12-24 10:23  振袖秋枫问红叶  阅读(42)  评论(0)    收藏  举报