Leetcode 215. Kth Largest Element in an Array 优先队列&快速选择

题目链接

快速选择

使用快速排序的partition方法,结合二分查找的思想。

class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k > nums.length) return 0;
        if (nums.length == 1) return 1;
        int lo = 0; 
        int hi = nums.length - 1;
        while (lo < hi) {
            System.out.println(hi);
            int index = partition(nums, lo, hi);
            if (index > k - 1) hi = index - 1;
            else if (index < k - 1) lo = index + 1;
            else return nums[index];
            // System.out.println(lo + " " + hi);
        }
        return nums[k - 1];
    }
    
    private int partition(int[] nums, int lo, int hi) {
        int pi = nums[lo]; // partitioning item
        int i = lo;
        int j = hi + 1;
        while (true) {
            while (nums[++i] > pi) if (i >= hi) break;
            while (nums[--j] < pi) if (j <= lo) break;
            if (i >= j) break;
            exch(nums, i, j);
        }
        exch(nums, lo, j);
        return j;
    }
    
    private void exch(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

注意二分搜索的条件为lo < hi,若lo与hi重合,会导致partition时越界。

优先队列

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for (int num : nums) queue.offer(num);
        while (queue.size() > k) queue.poll();
        return queue.peek();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值