当前位置:网站首页>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

原网站

版权声明
本文为[A goblin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261801123549.html