当前位置:网站首页>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
边栏推荐
- pycharm的plt.show()如何保持不关闭
- Get and set settings in 26class
- How does Guosen Securities open an account? Is it safe to open a stock account through the link
- 数据加密标准(DES)概念及工作原理
- JVM入个门(1)
- Let torch cuda. is_ Experience of available() changing from false to true
- wm_concat()和group_concat()函数
- ZCMU--1367: Data Structure
- Padding percentage operation
- Data Encryption Standard DES security
猜你喜欢
随机推荐
Several key points in divorce agreement
Get and set settings in 26class
Runtimeerror: CUDA error: out of memory own solution (it is estimated that it is not applicable to most people in special circumstances)
新手炒股开户选哪个证券公司比较好?怎样炒股比较安全??
Detailed explanation of dos and attack methods
17.13 supplementary knowledge, thread pool discussion, quantity discussion and summary
Deep understanding of MySQL lock and transaction isolation level
【QNX】命令
ros::spinOnce()和ros::spin()的使用和区别
MySQL的MVCC机制详解
JS 常用正则表达式
idea中文插件chinese(simplified) language pack
DoS及攻擊方法詳解
【Unity】在Unity中使用C#执行外部文件,如.exe或者.bat
如何将应用加入到deviceidle 白名单?
Padding percentage operation
深入理解MySQL锁与事务隔离级别
[npoi] C copy sheet template across workbooks to export Excel
RSA加密解密详解
Chen Qiang: Alibaba's 100 billion level large-scale digital business knowledge map helps business growth








