692. Top K Frequent Words:HashMap排序

因为平时工作中较少能接触到HashMap的排序,因此周末借由一道leetcode上的小题,再写一写HashMap的排序代码,特此记录。

原题如下:

  1. Top K Frequent Words

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:
Input: [“i”, “love”, “leetcode”, “i”, “love”, “coding”], k = 2
Output: [“i”, “love”]
Explanation: “i” and “love” are the two most frequent words.
Note that “i” comes before “love” due to a lower alphabetical order.

Example 2:
Input: [“the”, “day”, “is”, “sunny”, “the”, “the”, “the”, “sunny”, “is”, “is”], k = 4
Output: [“the”, “is”, “sunny”, “day”]
Explanation: “the”, “is”, “sunny” and “day” are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.

题目大意:

给出一个字符串数组和数字k,求前k个出现次数最高的字符串

思路:

先统计字符串出现次数、然后按照次数排序,注意:如果两个字符串出现次数相同,按照字典序排序;最后输出前k个字符串,简单粗暴;

代码:

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> map = new HashMap<>();
        // 统计单词次数
        for(String word : words) {
            if(!map.containsKey(word)) {
                map.put(word, 1);
                continue;
            }
            map.put(word, map.get(word) + 1);
        }
        // 对HashMap排序前,要把HashMap的键值对取出来,放入List中,然后对List排序
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        // 重写了compare方法,在里面自定义排序规则
        list.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                // 出现次数多,排到前面
                if (o1.getValue() > o2.getValue()) {
                    return -1;
                }
                // 如果出现次数相同,字典序小的排到前面
                if (o1.getValue().equals(o2.getValue())) {
                    if(o1.getKey().compareTo(o2.getKey()) < 0) {
                        return -1;
                    }
                    return 1;
                }
                if(o1.getValue() < o2.getValue()) {
                    return 1;
                }
                return 0;
            }
        });
        // 输出前k个
        List<String> result = new ArrayList<>(k);
        for(int i = 0; i < k; i++) {
            result.add(list.get(i).getKey());
        }
        return result;
    }
}

程序很简单,虽然AC了,但是耗时比较大。
692. Top K Frequent Words:HashMap排序_第1张图片

你可能感兴趣的:(LeetCode)