Medium
思路
思路很简单,走一遍map, key是元素,val是频率, 之后用一个pq, 设定size为k,每次size超过k就把频率最小的元素poll出,最后循环pq,返回数组
过程
- 在建立pq时注意, 因为我们是要在pq中存key, 每次poll出的是key值, 最后数组返回的也是key值, 但是每次比较的val值,也就是频率。
- 所以要在建立pq时后面写上:
- PriorityQueue pq = new PriorityQueue<>((n1, n2) -> map.get(n1) - map.get(n2));
- 同时注意最后把pq中的元素转回到数组时, 要预先把pq的size拿出来, 否则for循环的判定条件不对, 因为pq的size随着poll而变化。
代码
class Solution {
public int[] topKFrequent(int[] nums, int k) {
if(k == nums.length) return nums;
int[] res = new int[k];
Map<Integer, Integer> map = new HashMap<>();
PriorityQueue<Integer> pq = new PriorityQueue<>((n1, n2) -> map.get(n1) - map.get(n2));
for(int i = 0; i < nums.length; i++){
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}
for(int i : map.keySet()){
pq.offer(i);
if(pq.size() > k)
pq.poll();
}
int s = pq.size();
for(int i = 0; i < s; ++i) {
res[i] = pq.poll();
}
return res;
}
}
- 优先队列, hashmap
- 08/03/20