Leetcode 347: Top K Frequent Elements

題目描述:給定一個非空整數數組,返回數組中k個出現頻率最高的元素

輸入: nums = [1,1,1,2,2,3], k = 2

輸出:[1,2]    

解釋:由於對輸入的元素按出現頻率由高到低排序後是 [1,2,3] 返回k=2個元素,則返回值爲[1,2]

思路:

       1. HashMap 存儲 鍵值對 :   (k, v) = (元素:元素出現的次數)

       2. 根據HashMap中每個鍵對應的值進行 建立堆的工作。 可用優先隊列實現

注:

    優先隊列 基於二叉堆實現的, 二叉堆實際使用數組實現的

package Leetcode.Heap.TopKFrequentElements_347;

import java.util.*;

/**
 * leetcode 247
 */
public class Solution2 {
    public List<Integer> topKFrequent(int[] nums, int k){
        List<Integer> topk_list = new ArrayList<Integer>();
        HashMap<Integer, Integer> count = new HashMap<>();
        for (int i: nums){
            count.put(i, count.getOrDefault(i, 0)+1);
        }
        PriorityQueue<Integer> heap = new PriorityQueue<Integer>((n1, n2)->count.get(n1)-count.get(n2));
        for (int i: count.keySet()){
            heap.add(i);
            if (heap.size() > k){
                heap.poll();
            }
        }
        while (!heap.isEmpty()){
            topk_list.add(heap.poll());
        }
        Collections.reverse(topk_list);
        return topk_list;
    }

    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        int[] nums = {3, 2,2,1,1,1};
        int k = 2;
        List<Integer> list = solution2.topKFrequent(nums, 2);
        System.out.println(list);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章