1. 程式人生 > >[leetcode]692. Top K Frequent Words K個最常見單詞

[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個最常見元素思路完全一致

 

程式碼

 1 /*
 2 Time: O(nlogk)
 3 Space: O(n)
 4 */
 5 
 6 class Solution {
 7        public List<String> topKFrequent(String[] words, int k) {
 8          List<String> result = new LinkedList<>();
 9          // freq map 
10 Map<String, Integer> map = new HashMap<>(); 11 for(String s: words){ 12 map.put(s, map.containsKey(s) ? map.get(s) + 1 : 1); 13 } 14 // b.getKey().compareTo(a.getKey()) 處理了頻率相同,按字典順序排列的題意要求 15 PriorityQueue<Map.Entry<String, Integer>> minHeap = new PriorityQueue<>( 16 (a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue() 17 ); 18 19 for(Map.Entry<String, Integer> entry: map.entrySet()) 20 { 21 minHeap.offer(entry); 22 if(minHeap.size()>k) 23 // 自定義從小到大的順序保證了poll出來的是較小值,留在minHeap裡的是較大值 24 minHeap.poll(); 25 } 26 27 while(!minHeap.isEmpty()) 28 result.add(0, minHeap.poll().getKey()); 29 30 return result; 31 } 32 }