lintcode544 - Top k Largest Numbers -medium

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].
 
1.用堆数据结构。O(nlogk)时间复杂度,O(k)空间复杂度。
维护一个大小为k的小根堆,这个堆的定义是存储top k的容器。如果进来的数比堆顶大一点(就是击败了top k里最菜的人),那就替代。走完一轮堆里的元素就是top k了。
2.利用quick select。O(n*k)时间复杂度,O(1)空间复杂度。
因为quick select可以做到O(n)时间得到任意第k大数(kth largest number),那做k次quick select即可。
 
实现1:用堆数据结构
    public class Solution {
        /**
         * @param nums: an integer array
         * @param k: An integer
         * @return: the top k largest numbers in array
         */
        public int[] topk(int[] nums, int k) {
            // write your code here
            if (nums == null || k <= 0 || k > nums.length) {
                return nums;
            }
            PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k);
            for (int num : nums) {
                if (pq.size() < k) {
                    pq.offer(num);
                } else if (num > pq.peek()){
                    pq.poll();
                    pq.offer(num);
                }
            }
            int[] result = new int[k];
            for (int i = k - 1; i >= 0; i--) {
                result[i] = pq.poll();
            }
            return result;
        }
    }

 

posted @ 2018-09-06 03:43  jasminemzy  阅读(257)  评论(0编辑  收藏  举报