题目描述
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
样例
示例 1:
输入: [“i”, “love”, “leetcode”, “i”, “love”, “coding”], k = 2
输出: [“i”, “love”]
解析: “i” 和 “love” 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 “i” 在 “love” 之前。
示例 2:
输入: [“the”, “day”, “is”, “sunny”, “the”, “the”, “the”, “sunny”, “is”, “is”], k = 4
输出: [“the”, “is”, “sunny”, “day”]
解析: “the”, “is”, “sunny” 和 “day” 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
思路
使用一个哈希表,记录每个单词的出现次数。
然后把所有的单词加入到一个 List 中,按照出现的次数进行排序。
最后取 List 前 k 个元素作为子集,输出答案。
代码
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map <String,Integer> mp = new HashMap<String, Integer>();
//记录
for(int i = 0;i < words.length;i++) {
mp.put(words[i], mp.getOrDefault(words[i], 0)+1);
}
//列表存储words
List <String> lst = new ArrayList<String>();
for(Map.Entry<String, Integer> entry : mp.entrySet()) {
lst.add(entry.getKey());
}
//排序得到前k个
Comparator<String> c = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if(mp.get(o1) == mp.get(o2))
return o1.compareTo(o2);
else
return mp.get(o2) - mp.get(o1);
}
};
Collections.sort(lst, c);
//取前k个子集
return lst.subList(0, k);
}
}