1. 程式人生 > 其它 >347. 前K個高頻元素

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/