347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

分析:

http://blog.csdn.net/itismelzp/article/details/51451374

bucket sort, 出现次数作为被sort的对象。

 1 public class Solution {
 2     public int[] topKFrequent(int[] nums, int k) {
 3         Map<Integer, Integer> map = new HashMap<>();
 4         for (int num : nums) {
 5             map.put(num, map.getOrDefault(num, 0) + 1);
 6         }
 7         // worst case, all values in nums are the same.
 8         // Therefore, the size of buckets should be nums.length + 1
 9         List<Integer>[] bucket = new List[nums.length + 1];
10         for (int key : map.keySet()) {
11             int value = map.get(key);
12             if (bucket[value] == null) {
13                 bucket[value] = new ArrayList<>();
14             }
15             bucket[value].add(key);
16         }
17 
18         int[] result = new int[k];
19         int pointer = 0;
20         for (int i = bucket.length - 1; i >= 0; i--) {
21             if (bucket[i] != null) {
22                 for (int num : bucket[i]) {
23                     if (pointer < k) {
24                         result[pointer] = num;
25                         pointer++;
26                     } else {
27                         break;
28                     }
29                 }
30             }
31         }
32         return result;
33     }
34 }

 

使用min heap.

 1 class Solution {
 2         public int[] topKFrequent(int[] nums, int k) {
 3         Map<Integer, Integer> map = new HashMap<>();
 4         for (int n : nums) {
 5             map.put(n, map.getOrDefault(n, 0) + 1);
 6         }
 7 
 8         PriorityQueue<Map.Entry<Integer, Integer>> minPQ = new PriorityQueue<>(k + 1,
 9                 (a, b) -> a.getValue().compareTo(b.getValue()));
10         
11         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
12             minPQ.add(entry);
13             if (minPQ.size() > k) {
14                 minPQ.poll();
15             }
16         }
17 
18         List<Integer> res = new LinkedList<>();
19         while (!minPQ.isEmpty()) {
20             Map.Entry<Integer, Integer> entry = minPQ.poll();
21             res.add(0, entry.getKey());
22         }
23         return res.stream().mapToInt(i -> i).toArray();
24     }
25 }

 

posted @ 2016-07-27 01:24  北叶青藤  阅读(214)  评论(0)    收藏  举报