当前位置:网站首页>PriorityQueue (large root heap / small root heap /topk problem)
PriorityQueue (large root heap / small root heap /topk problem)
2022-07-06 13:36:00 【Li bohuan】
PriorityQueue It's from JDK1.5 Start to provide new data structure interface , It's a very high priority queue based on priority heap . Priority queue is another kind of queue different from FIFO queue . Each time the element with the highest priority is removed from the queue .
By default ,PriorityQueue yes Small cap pile , As the code shows
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
queue.offer(6);
while (!queue.isEmpty()){
System.out.print(queue.poll() + " ");
}
}Output results :

We can also construct it in the following ways Big pile top :
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>((o1,o2) -> o2 - o1);// Descending
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
queue.offer(6);
while (!queue.isEmpty()){
System.out.print(queue.poll() + " ");
}
}Output results :

Top K problem , Power button 347 Heli button 692:
Power button 347: Give you an array of integers nums And an integer k , Please return to the frequency before k High element . You can press In any order Return to the answer .
Example :
Input : nums = [1,1,1,2,2,3], k = 2 Output : [1,2]
The code is as follows : Pay attention to the construction of small top pile (o1,o2)-> o1.getValue() - o2.getValue() Don't omit .
public int[] topKFrequent(int[] nums, int k) {
//key Element value ,value For frequency of occurrence
HashMap<Integer,Integer> map = new HashMap<>();
PriorityQueue<Map.Entry<Integer, Integer>> queue
= new PriorityQueue<>((o1,o2)-> o1.getValue() - o2.getValue());
int[] res = new int[k];
for (int num : nums) {
map.put(num,map.getOrDefault(num,0) + 1);
}
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
queue.offer(entry);
if(queue.size() > k){
queue.poll();
}
}
// What remains is the most frequent
for(int i = 0; i < k; i++){
Map.Entry<Integer, Integer> poll = queue.poll();
res[i] = poll.getKey();
}
return res;Power button 692: Given a list of words words And an integer k , Return to the former k The most frequently used word . The answers returned should be sorted by word frequency from high to low . If different words have the same frequency , Sort in dictionary order .
Example :
Input : words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output : ["i", "love"]
analysis : "i" and "love" For the two words that appear most frequently , Are all 2 Time . Be careful , In alphabetical order "i" stay "love" Before .
This question is a little more difficult than the last one , Because when two words appear the same number of times, we should also consider sorting by dictionary , The second is that the answers need to be sorted from top to bottom , This is mainly reflected in the priority queue PriorityQueue On the structure of . The code is as follows :
public List<String> topKFrequent(String[] words, int k) {
List<String> res = new ArrayList<>();
//key For the elements ,value For frequency of occurrence
HashMap<String,Integer> map = new HashMap<>();
for (String word : words) {
map.put(word,map.getOrDefault(word,0) + 1);
}
PriorityQueue<Map.Entry<String,Integer>> queue = new PriorityQueue<>(
((o1, o2) -> {
if(o1.getValue() == o2.getValue()){
return o2.getKey().compareTo(o1.getKey());
}
return o1.getValue() - o2.getValue();
})
);
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
queue.offer(entry);
if(queue.size() > k){
queue.poll();
}
}
for(int i = 0; i < k; i++){
res.add(queue.poll().getKey());
}
Collections.reverse(res);
return res;
}Be careful o2.getKey().compareTo(o1.getKey()) Is in reverse order of the dictionary , Why do that , Because we use a small top pile here , So every time poll What comes out is the smallest frequency element , Last need reverse once , In order to cooperate with this , So when we construct the priority queue, we use the reverse order of the dictionary .
边栏推荐
猜你喜欢

Design a key value cache to save the results of the most recent Web server queries

3. Number guessing game

3.输入和输出函数(printf、scanf、getchar和putchar)

C语言入门指南

甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1

MySQL事务及实现原理全面总结,再也不用担心面试

Mortal immortal cultivation pointer-1

Common method signatures and meanings of Iterable, collection and list

Tyut Taiyuan University of technology 2022 "Mao Gai" must be recited

2. Preliminary exercises of C language (2)
随机推荐
5月14日杂谈
C语言实现扫雷游戏(完整版)
[while your roommate plays games, let's see a problem]
Arduino+ds18b20 temperature sensor (buzzer alarm) +lcd1602 display (IIC drive)
1.初识C语言(1)
[中国近代史] 第五章测验
稻 城 亚 丁
IPv6 experiment
9. Pointer (upper)
Alibaba cloud microservices (I) service registry Nacos, rest template and feign client
8.C语言——位操作符与位移操作符
重载和重写的区别
String abc = new String(“abc“),到底创建了几个对象
【九阳神功】2018复旦大学应用统计真题+解析
View UI Plus 发布 1.3.1 版本,增强 TypeScript 使用体验
魏牌:产品叫好声一片,但为何销量还是受挫
MySQL limit x, -1 doesn't work, -1 does not work, and an error is reported
View UI plus released version 1.2.0 and added image, skeleton and typography components
7.数组、指针和数组的关系
六种集合的遍历方式总结(List Set Map Queue Deque Stack)