[leetcode]347. Top K Frequent Elements 最高频的前K个元素

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

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

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.

题意:

给定数组,求其中出现频率最高的K个元素。

Solution: PriorityQueue

扫数组,将数组每个元素和其对应的出现频率存到Map里

扫Map,将Map里的元素放入maxHeap

从maxHeap里poll出K个元素即可

code

 class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> numFreqs = new HashMap(); for(int num : nums){
numFreqs.put(num, numFreqs.containsKey(num) ? numFreqs.get(num) + 1 : 1);
} PriorityQueue <Map.Entry<Integer, Integer>> maxHeap = new PriorityQueue<>((entry1, entry2) -> entry2.getValue() - entry1.getValue()); for(Map.Entry<Integer, Integer> entry : numFreqs.entrySet()){
maxHeap.add(entry);
} List<Integer> result = new ArrayList<>();
while(!maxHeap.isEmpty() && result.size() < k){
result.add(0, maxHeap.poll().getKey());
}
return result; }
}
上一篇:[leetcode]347. Top K Frequent Elements K个最常见元素


下一篇:Java核心-01 谈谈你对Java平台的理解