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了,但是耗时比较大。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值