[leetcode]692. Top K Frequent Words K个最常见单词

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

题目

思路

1. Using HashMap and PriorityQueue
2. Build a HashMap to get the word frequency
3. PriorityQueue (minHeap) - if the counts are same return higher lexicographically word first so that the lower remains in the queue
4. We add each entry to PQ. If the PQ size > k, then we pop the lowest value in the PQ.

[leetcode]347. Top K Frequent Elements K个最常见元素思路完全一致

代码

 /*
Time: O(nlogk)
Space: O(n)
*/ class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> result = new LinkedList<>();
// freq map
Map<String, Integer> map = new HashMap<>();
for(String s: words){
map.put(s, map.containsKey(s) ? map.get(s) + 1 : 1);
}
// b.getKey().compareTo(a.getKey()) 处理了频率相同,按字典顺序排列的题意要求
PriorityQueue<Map.Entry<String, Integer>> minHeap = new PriorityQueue<>(
(a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue()
); for(Map.Entry<String, Integer> entry: map.entrySet())
{
minHeap.offer(entry);
if(minHeap.size()>k)
// 自定义从小到大的顺序保证了poll出来的是较小值,留在minHeap里的是较大值
minHeap.poll();
} while(!minHeap.isEmpty())
result.add(0, minHeap.poll().getKey()); return result;
}
}
上一篇:使用 Azure CLI 在 Azure China Cloud 云平台上手动部署一套 Cloud Foundry


下一篇:C#进程同名的问题