当前位置:网站首页>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
边栏推荐
- 网络通讯之Socket-Tcp(一)
- Why can't my MySQL container start
- SystemVerilog -- OOP -- copy of object
- PHP export word method (phpword)
- regular expression
- Apprendre à concevoir des entités logicielles réutilisables à partir de la classe, de l'API et du cadre
- AOSP ~ NTP (Network Time Protocol)
- Sheet1$. Output [excel source output] Error in column [xxx]. The returned column status is: "the text is truncated, or one or more characters have no matches in the target code page.".
- DEJA_ Vu3d - 054 of cesium feature set - simulate the whole process of rocket launch
- Vulnhub geminiinc V2
猜你喜欢
随机推荐
ArcGIS application (XXI) ArcMap method of deleting layer specified features
Groovy test class and JUnit test
Redis
Flutter Widget : KeyedSubtree
Qt OpenGL 纹理贴图
Kubernetes three dozen probes and probe mode
(construction notes) learning experience of MIT reading
Vulnhub's Tomato (tomato)
Fluent: Engine Architecture
Shutter: about inheritedwidget
Socket TCP for network communication (I)
Basic knowledge of OpenGL (sort it out according to your own understanding)
Vulnhub's cereal
Wechat applet - basic content
Swagger
Colleagues wrote a responsibility chain model, with countless bugs
Go language to realize static server
Solve msvcp120d DLL and msvcr120d DLL missing
vulnhub之momentum
Deploying WordPress instance tutorial under coreos