Leetcode 347. Top K Frequent Elements
题目
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]Input: nums = [1], k = 1
Output: [1]思路
解答
Complexity Analysis
拓展
总结
Reference
Last updated
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]Input: nums = [1], k = 1
Output: [1]Last updated
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
// Count numbers
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : nums) map.put(i, map.getOrDefault(i, 0) + 1);
// Priority queue that less frequent get poll first
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((n1, n2) -> map.get(n1) - map.get(n2));
for (Integer n : map.keySet()) {
pq.offer(n);
if (pq.size() > k)
pq.poll(); // maintain only k most frequent
}
// Formulate result
List<Integer> res = new ArrayList<Integer>();
while (! pq.isEmpty())
res.add(pq.poll());
Collections.reverse(res);
return res;
}
}