当前位置:网站首页>347. Top k high frequency elements
347. Top k high frequency elements
2022-07-03 12:11:00 【zwanying】
Find the number of elements , Think of using map Recording .
front k High frequency elements : Sort .
map Cannot sort values , Replaceable map Key position , Or a map Turn into list To achieve .
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap();
// Record times
for(int i : nums){
if(map.containsKey(i)){
map.put(i,map.get(i)+1);
}else{
map.put(i,1);
}
}
// Sort
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue()-o1.getValue();
}
});
int i =0;
nums = new int[k];
for (Map.Entry<Integer, Integer> e: list) {
nums[i++]=e.getKey();
if(i>=k){
break;
}
}
return nums;
}
}
Knowledge point :
map Cannot sort values directly , We need to convert to list, Use Collections.sort Sort .
The sorting time is either greater than , Or less than , Or equal to , There can be no ambiguity , Unable to determine the size .
o1>o2 It's in ascending order .
Other answers :
The most appropriate data structure : Priority queue .( Pile up , Perfect binary tree ), It can sort the data .
PriorityQueue<Map.Entry<Integer,Integer>> queue =
new PriorityQueue<>((o1,o2)-> o1.getValue-o2.getValue);
Knowledge point :
Priority queues use
Rewrite sorting method
offer == set
poll == get And delete
边栏推荐
- C language improvement article (wchar_t) character type
- [combinatorics] permutation and combination (example of permutation and combination)
- vulnhub之GeminiInc v2
- Cacti monitors redis implementation process
- shardingSphere分库分表<3>
- Wechat applet development - page Jump transfer parameters
- Vulnhub narak
- temp
- MySQL time zone solution
- Ripper of vulnhub
猜你喜欢
STL tutorial 10 container commonalities and usage scenarios
PHP export word method (one MHT)
【mysql官方文档】死锁
4000 word super detailed pointer
Basic knowledge of OpenGL (sort it out according to your own understanding)
Momentum of vulnhub
STL Tutorial 9 deep copy and shallow copy of container elements
Visual studio 2022 downloading and configuring opencv4.5.5
vulnhub之Nagini
[MySQL special] read lock and write lock
随机推荐
DNS multi-point deployment IP anycast+bgp actual combat analysis
Ripper of vulnhub
vulnhub之raven2
Simple factory and factory method mode
Dart: About zone
Swagger
Quantitative calculation research
Laravel time zone timezone
vulnhub之momentum
Qt OpenGL 纹理贴图
Vulnhub's presidential
为什么我的mysql容器启动不了呢
MySQL searches and sorts out common methods according to time
Qt OpenGL相机的使用
Shutter: add gradient stroke to font
Shutter: about inheritedwidget
How to deploy web pages to Alibaba cloud
Optimize interface performance
Socket TCP for network communication (I)
Notes on 32-96 questions of sword finger offer