Top k Largest Numbers

Given an integer array, find the top k largest numbers in it.

Example

Given [3,10,1000,-99,4,100] and k = 3.
Return [1000, 100, 10].

思路:由于需要按从大到小的顺序,因此直接用PriorityQueue即可,用Partition的方法的话还需要排序。直接用PriorityQueue 写的代码量少。
 1 class Solution {
 2     /*
 3      * @param nums an integer array
 4      * @param k an integer
 5      * @return the top k largest numbers in array
 6      */
 7     public int[] topk(int[] nums, int k) {
 8         if (nums == null || nums.length < k) {
 9             return null;
10         }
11         
12         int[] result = new int[k];
13         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
14         for (int i = 0; i < nums.length; i++) {
15             if (minHeap.size() < k) {
16                 minHeap.add(nums[i]);
17             } else {
18                 int temp = minHeap.poll();
19                 minHeap.add(Math.max(temp, nums[i]));
20             }
21         }
22         
23         for (int i = k - 1; i >= 0; i--) {
24             result[i] = minHeap.poll();
25         }
26         
27         return result;
28     }
29 };

 

posted @ 2016-05-29 19:40  YuriFLAG  阅读(378)  评论(0)    收藏  举报