Leetcode 692: Top K Frequent Words

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.

 

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.

 

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

 

Follow up:

  1. Try to solve it in O(n log k) time and O(n) extra space.
 1 public class Solution {
 2     public IList<string> TopKFrequent(string[] words, int k) {
 3         var result = new List<string>();
 4         
 5         if (words == null || words.Length == 0 || k < 1) return result;
 6         
 7         var dict = new SortedDictionary<string, int>();
 8         
 9         foreach (var w in words)
10         {
11             if (dict.ContainsKey(w))
12             {
13                 dict[w]++;
14             }
15             else
16             {
17                 dict[w] = 1;
18             }
19         }
20         
21         var buckets = new List<string>[words.Length + 1];
22         foreach (var pair in dict)
23         {
24             if (buckets[pair.Value] == null)
25             {
26                 buckets[pair.Value] = new List<string>();
27             }
28             
29             buckets[pair.Value].Add(pair.Key);            
30         }
31         
32         for (int i = buckets.Length - 1; i >= 0; i--)
33         {
34             if (buckets[i] != null)
35             {
36                 foreach (var s in buckets[i])
37                 {
38                     result.Add(s);
39             
40                     if (result.Count >= k) return result;
41                 }
42             }
43         }
44         
45         return result;
46     }
47 }

 

posted @ 2018-02-04 13:28  逸朵  阅读(144)  评论(0编辑  收藏  举报