Leetcode每日一题-2021/05/20-前K个高频单词
前K个高频单词
方法一:哈希表+排序
思路:首先将字符串的出现次数存储在哈希表中(字符串作key,次数作value),然后根据出现次数将其进行排序(从大到小),
如果出现次数一样,则按字典序排序。最后返回排序后的前K个字符。
代码如下:
class Solution {
// 哈希表+排序
public List<String> topKFrequent(String[] words, int k) {
Map<String,Integer> map = new HashMap<>();
List<String> res = new LinkedList<>();
for( int i = 0; i < words.length; ++i ){
String word = words[i];
map.put(word,map.getOrDefault(word,0) + 1);
}
Set<Map.Entry<String,Integer>> set = map.entrySet();
while(k-- > 0){
List<String> temp = new LinkedList<>();
int maxVal = Integer.MIN_VALUE;
for( Map.Entry<String,Integer> entry : map.entrySet() ){
maxVal = maxVal > entry.getValue() ? maxVal : entry.getValue();
}
for( Map.Entry<String,Integer> entry : map.entrySet() ){
if( maxVal == entry.getValue() ){
temp.add(entry.getKey());
}
}
String strs[] = temp.toArray(new String[]{});
Arrays.sort(strs);
res.add(strs[0]);
map.remove(strs[0]);
}
return res;
}
}
作者:mai-jia-jun
链接:https://leetcode-cn.com/problems/top-k-frequent-words/solution/qian-kge-gao-pin-dan-ci-by-mai-jia-jun-0zf9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法二:优先队列
优先队列定义:
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,
具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。通常采用堆数据结构来实现。
思路:首先将字符串的出现次数存储在哈希表中(字符串作key,次数作value),创建优先队列,并定义优先队列的排序规则。然后
往优先队列中添加字符,如果优先队列中的元素数量大于了K,则将队列中优先级最高的元素移出队列。最后将结果集逆序返回即可。