Top K Frequent Words
来源:互联网 发布:福昕阅读器破解版mac 编辑:程序博客网 时间:2024/06/05 19:50
Given a list of words and an integer k, return the top k frequent words in the list.
Notice
You should order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first.
Example
Given
[ "yes", "lint", "code", "yes", "code", "baby", "you", "baby", "chrome", "safari", "lint", "code", "body", "lint", "code"]
for k = 3
, return ["code", "lint", "baby"]
.
for k = 4
, return ["code", "lint", "baby", "yes"]
,
使用heap sort的方式去做,其中的一个重点是自定义比较器
定义比较器的时候,首相是按照出现的次数进行定义,当出现的此时相同时,然后在按照字典顺序进行排序,在使用String中的compareTo方法时,需要注意的一点是,String的compareTo方法的返回值与compare中要求的返回值的类型一直但是数值相反,因此要反向使用。
java
class Type { String word; int count; public Type(String word, int count) { this.word = word; this.count = count; }}public class Solution { /* * @param words: an array of string * @param k: An integer * @return: an array of string */ public String[] topKFrequentWords(String[] words, int k) { // write your code here if (words == null || words.length == 0) { return words; } if (k == 0) { return new String[]{}; } Comparator<Type> cmp = new Comparator<Type>() { public int compare(Type a, Type b) { if (a.count != b.count) { return a.count - b.count; } else { return b.word.compareTo(a.word); } } }; Queue<Type> heap = new PriorityQueue<>(k, cmp); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < words.length; i++) { if (map.containsKey(words[i])) { map.put(words[i], map.get(words[i]) + 1); } else { map.put(words[i], 1); } } for (String str : map.keySet()) { Type type = new Type(str, map.get(str)); heap.offer(type); if (heap.size() > k) { heap.poll(); } } String[] res = new String[k--]; while (!heap.isEmpty()) { res[k--] = heap.poll().word; } return res; }}
阅读全文
0 0
- Top K Frequent Words
- [刷题]Top K Frequent Words
- 692. Top K Frequent Words
- 692. Top K Frequent Words
- Top K Frequent Words问题及解法
- leetcode 692. Top K Frequent Words
- LeetCode 692. Top K Frequent Words
- LeetCode 692. Top K Frequent Words
- LeetCode.347(692) Top K Frequent Elements && Top K Frequent Words
- LeetCode算法题——Top K Frequent Words
- Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- Top K Frequent Elements
- IDEA报: Lombok Requires Annotation Processing
- 线程的状态
- c的数据类型
- 对逻辑斯谛回归使用sigmoid的理解
- “抽象”的级别
- Top K Frequent Words
- 微信公众号转换短链接,短网址,php开发公众号生成短链接
- 天气插件
- 整合SpringIOC和SpringMVC
- 自动微分(Automatic Differentiation)简介
- JAVA泛型
- 刷题
- 关于Android的BroadcastReceiver的onReceive方法中回调结果给Activity的问题
- 2017中国长春第八届连锁加盟创业项目展览会会刊(参展商名录)