zoukankan      html  css  js  c++  java
  • lintcode544

    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;
            }
        }
  • 相关阅读:
    sed 练习
    正则表达式
    字符转换命令
    命令执行判断依据
    shell 操作环境
    选取命令
    排序命令
    命令别名与历史命令
    变量的学习
    防止恶意跳转
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9595918.html
Copyright © 2011-2022 走看看