当前位置:网站首页>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 .
边栏推荐
猜你喜欢
Alibaba cloud microservices (II) distributed service configuration center and Nacos usage scenarios and implementation introduction
Questions and answers of "Fundamentals of RF circuits" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
2. C language matrix multiplication
Alibaba cloud microservices (I) service registry Nacos, rest template and feign client
hashCode()与equals()之间的关系
关于双亲委派机制和类加载的过程
优先队列PriorityQueue (大根堆/小根堆/TopK问题)
4.分支语句和循环语句
7. Relationship between array, pointer and array
5. Function recursion exercise
随机推荐
Arduino+ds18b20 temperature sensor (buzzer alarm) +lcd1602 display (IIC drive)
[while your roommate plays games, let's see a problem]
FileInputStream和BufferedInputStream的比较
5月14日杂谈
2. Preliminary exercises of C language (2)
View UI plus released version 1.3.0, adding space and $imagepreview components
12 excel charts and arrays
Introduction and use of redis
Redis实现分布式锁原理详解
[中国近代史] 第九章测验
8. C language - bit operator and displacement operator
View UI plus released version 1.2.0 and added image, skeleton and typography components
MySQL锁总结(全面简洁 + 图文详解)
Wei Pai: the product is applauded, but why is the sales volume still frustrated
The latest tank battle 2022 - Notes on the whole development -2
IPv6 experiment
透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
C语言实现扫雷游戏(完整版)
C language Getting Started Guide
Comparison between FileInputStream and bufferedinputstream