当前位置:网站首页>Comparing the size relationship between two objects turns out to be so fancy
Comparing the size relationship between two objects turns out to be so fancy
2022-06-26 18:10:00 【A goblin】
One , Let's look at the topic first
Give a non empty list of words , 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 alphabetically .
Do you have an idea after reading the title ??????
TopK???
NO!!!
( Take your time )
Two , Their thinking
1. With the help of Map Count the number of occurrences of each word
2. Organize key value pairs into a ArrayList in
3. Sort in descending order according to the requirements of the topic ( Number of occurrences + Dictionary order )
Not much to say !!!! Here's the point
3、 ... and , Code up ( Here's the point )
First put the statistical results into a ArrayList
public List<String> topKFrequent(String[] words,int k){
// First count the number of occurrences of each word
Map<String,Integer> map = new HashMap<>();
for (String s : words ) {
int count = map.getOrDefault(s,0);// Get the number of occurrences of the current word
map.put(s,count+1);// Deposit in map in
}
// Put the string just counted into ArrayList in
//KeySet It's equivalent to getting a Set,Set What is stored in the is all key
ArrayList<String> arrayList = new ArrayList(map.keySet());
// According to the statistics just now , in the light of ArrayList Sort
Then the performance began
1. Use collection classes Collections Self contained sort Method pair ArrayList Sort
Be careful : sort By default, the elements are sorted in ascending order according to their own size (String Dictionary sequence ) Here we will sort the string in descending order according to the number of occurrences , Therefore we need Comparator customizes comparison rules
reflection : Here we use Comparable OK? ???
answer : no way reason : Because we are aiming at String Make comparison rules , To compare, you need to change String Source code , Can you change ?
So we have to rewrite a comparator , To specify the String What is big , What is small
static class MyComparator implements Comparator<String>{
private Map<String,Integer> map;
public MyComparator(Map<String, Integer> map) {
this.map = map;
}
@Override
public int compare(String o1, String o2) {
int count1 =map.get(o1);
int count2 = map.get(o2);
if(count1 == count2){
//String Self actualization Comparable, With dictionary order comparison function
//CompareTo Is the use of String The default comparison rule
return o1.compareTo(o2);
}
return count2-count1;
}
}
public List<String> topKFrequent(String[] words,int k){
// First count the number of occurrences of each word
Map<String,Integer> map = new HashMap<>();
for (String s : words ) {
int count = map.getOrDefault(s,0);// Get the number of occurrences of the current word
map.put(s,count+1);// Deposit in map in
}
// Put the string just counted into ArrayList in
//KeySet It's equivalent to getting a Set,Set What is stored in the is all key
ArrayList<String> arrayList = new ArrayList(map.keySet());
Collections.sort(arrayList,new MyComparator(map));
return arrayList.subList(0,k);
}
2. Use anonymous inner class ( Grammatical sugar )
When to use an internal anonymous class ??
This class is used only once , I lost it when I used it up
public List<String> topKFrequent(String[] words,int k){
// First count the number of occurrences of each word
Map<String,Integer> map = new HashMap<>();
for (String s : words ) {
int count = map.getOrDefault(s,0);// Get the number of occurrences of the current word
map.put(s,count+1);// Deposit in map in
}
// Put the string just counted into ArrayList in
//KeySet It's equivalent to getting a Set,Set What is stored in the is all key
ArrayList<String> arrayList = new ArrayList(map.keySet());
Collections.sort(arrayList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int count1 = map.get(o1);
int count2 = map.get(o2);
if(count1 == count2){
return o1.compareTo(o2);
}
return count2-count1;
}
});
return arrayList.subList(0,k);
}
3. Use lambda expression ( Grammatical sugar )
lambda expression , It's essentially an anonymous method
public List<String> topKFrequent(String[] words,int k){
// First count the number of occurrences of each word
Map<String,Integer> map = new HashMap<>();
for (String s : words ) {
int count = map.getOrDefault(s,0);// Get the number of occurrences of the current word
map.put(s,count+1);// Deposit in map in
}
// Put the string just counted into ArrayList in
//KeySet It's equivalent to getting a Set,Set What is stored in the is all key
ArrayList<String> arrayList = new ArrayList(map.keySet());
Collections.sort(arrayList, (o1, o2) ->{
int count1 = map.get(o1);
int count2 = map.get(o2);
if(count1 == count2){
return o1.compareTo(o2);
}
return count2-count1;
});
return arrayList.subList(0,k);
}
These two candies are hard candies , Take your time
边栏推荐
- In and exceptions, count (*) query optimization
- sql 中的alter操作总结
- 【NPOI】C#跨工作薄复制Sheet模板导出Excel
- How to add an application to the deviceidle whitelist?
- Runtimeerror: CUDA error: out of memory own solution (it is estimated that it is not applicable to most people in special circumstances)
- Applet setting button sharing function
- 小程序设置按钮分享功能
- MySQL download and configuration MySQL remote control
- 你好,现在网上股票开户买股票安全吗?
- DVD-数字通用光盘
猜你喜欢
随机推荐
ZCMU--1367: Data Structure
深层次安全定义剖析及加密技术
请指教同花顺开户选选择哪家券商比较好?现在在线开户安全么?
Bayesian network explanation
股票开账户如何优惠开户?现在在线开户安全么?
Case study of row lock and isolation level
transforms.RandomCrop()的输入只能是PIL image 不能是tensor
padding百分比操作
How pycharm modifies multiline annotation shortcuts
Clion编译catkin_ws(ROS工作空间包的简称)加载CMakeLists.txt出现的问题
wechat_微信小程序中解决navigator进行页面跳转并传递参数问题
Idea collection code, quickly open favorites collection window
[QNX] Command
idea中文插件chinese(simplified) language pack
How to add an application to the deviceidle whitelist?
力扣每日一题-第28天-566.重塑矩阵
RuntimeError: CUDA error: out of memory自己的解决方法(情况比较特殊估计对大部分人不适用)
Several key points in divorce agreement
sql 中的alter操作总结
17.13 补充知识、线程池浅谈、数量谈、总结