首页 > 其他 > 详细

Top K Frequent Words

时间:2016-04-06 13:15:19      阅读:210      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!