码迷,mamicode.com
首页 > 其他好文 > 详细

Top K Frequent Words

时间:2016-04-06 13:17:13      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

Given a list of words and an integer k, return the top k frequent words in the list.

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.

[
    "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"],

思路:Hash map + PriorityQueue(最小元素在顶部) + 定义 compare

 1 class Pair {
 2     String key;
 3     int value;
 4     
 5     Pair(String key, int value) {
 6         this.key = key;
 7         this.value = value;
 8     }
 9 }
10 
11 public class Solution {
12     /**
13      * @param words an array of string
14      * @param k an integer
15      * @return an array of string
16      */
17      
18     private Comparator<Pair> pairComparator = new Comparator<Pair>() {
19         public int compare(Pair left, Pair right) {
20             if (left.value != right.value) {
21                 return left.value - right.value > 0 ? 1 : -1;
22             }
23             return right.key.compareTo(left.key);
24         }
25     };
26     
27     public String[] topKFrequentWords(String[] words, int k) {
28         if (k == 0) {
29             return new String[0];
30         }
31         
32         HashMap<String, Integer> counter = new HashMap<>();
33         for (String word : words) {
34             if (counter.containsKey(word)) {
35                 counter.put(word, counter.get(word) + 1);
36             } else {
37                 counter.put(word, 1);
38             }
39         }
40         
41         PriorityQueue<Pair> Q = new PriorityQueue<Pair>(k, pairComparator);
42         for (String word : counter.keySet()) {
43             Pair peak = Q.peek();
44             Pair newPair = new Pair(word, counter.get(word));
45             if (Q.size() < k) {
46                 Q.add(newPair);
47             } else if (pairComparator.compare(newPair, peak) > 0) {
48                 Q.poll();
49                 Q.add(new Pair(word, counter.get(word)));
50             }
51         }
52         
53         String[] result = new String[k];
54         int index = 0;
55         while (!Q.isEmpty()) {
56             result[index++] = Q.poll().key;
57         }
58         for (int i = 0; i < result.length / 2; i++) {
59             String tmp = result[i];
60             result[i] = result[result.length - i - 1];
61             result[result.length - i - 1] = tmp;
62         }
63         return result;
64     }
65 }

 

Top K Frequent Words

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5358465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!