347. Top K Frequent Elements

用了新的结构~priorityQueue,记得再看看用法哦

 1     public List<Integer> topKFrequent(int[] nums, int k) {
 2         List<Integer> res = new ArrayList<Integer>();
 3         if(nums.length == 0) {
 4             return res;
 5         }
 6         PriorityQueue<Entry<Integer, Integer>> pq = new PriorityQueue<Entry<Integer, Integer>>(
 7             new Comparator<Entry<Integer, Integer>>() {
 8                 public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
 9                     return o1.getValue() - o2.getValue();
10                 }
11             });
12         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
13         for(int i = 0; i < nums.length; i++) {
14             if(map.containsKey(nums[i])) {
15                 map.put(nums[i], map.get(nums[i]) + 1);
16             } else {
17                 map.put(nums[i], 1);
18             }
19         }
20         for(Entry<Integer, Integer> entry: map.entrySet()) {
21             if(pq.size() < k) {
22                 pq.add(entry);
23             } else {
24                 if(pq.peek().getValue() < entry.getValue()) {
25                     pq.poll();
26                     pq.add(entry);
27                 }
28             }
29         }
30         while(!pq.isEmpty()) {
31             Entry<Integer, Integer> entry = pq.poll();
32             res.add(0, entry.getKey());
33         }
34         return res;
35     }

 

posted @ 2016-06-29 05:05  warmland  阅读(125)  评论(0编辑  收藏  举报