题目
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例1
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例1
输入: nums = [1], k = 1
输出: [1]
说明
1.你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
2.你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
题解
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
//用映射存储频次
HashMap<Integer,Integer> map=new HashMap();
for(int num:nums){
if(!map.containsKey(num)){
map.put(num,1);
}else{
map.put(num,map.get(num)+1);
}
}
//定义优先队列 ,底层实现默认最小堆
PriorityQueue<Integer> heap =
new PriorityQueue<Integer>((n1, n2) -> map.get(n1) - map.get(n2));// java8中的lamda表达式,(匿名类)
//放入优先队列
for (int n: map.keySet()) {
heap.add(n);
if (heap.size() > k)
heap.poll();
}
// 全部出队
List<Integer> top_k = new LinkedList();
while (!heap.isEmpty())
top_k.add(heap.poll());
Collections.reverse(top_k);
return top_k;
}
}