LintCode 5 / LeetCode 215 Kth Largest Element

本文深入探讨了快速选择算法,一种高效的查找第K大的元素的方法。文章详细解释了算法的思路,即通过partition过程实现,其时间复杂度为O(n),空间复杂度为O(n)。并提供了完整的Java代码实现,包括如何进行快速选择的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

quick select / partition(二者是一个东西)

复杂度

时间复杂度O(n)
空间复杂度O(n)

代码

public class Solution {
    /**
     * @param n: An integer
     * @param nums: An array
     * @return: the Kth largest element
     */
    public int kthLargestElement(int n, int[] nums) {
        // write your code here
        if (nums == null) {
            return -1;
        }
        
        return quickSelect(nums, 0, nums.length - 1, n);
    }
    
    private int quickSelect(int[] nums, int start, int end, int k) {
        if (start >= end) {
            return nums[start];
        }
        
        int left = start, right = end;
        int pivot = nums[(left + right) / 2];
        
        while (left <= right) {
            while (left <= right && nums[left] > pivot) {
                left++;
            }
            while (left <= right && nums[right] < pivot) {
                right--;
            }
            
            if (left <= right) {
                int t = nums[left];
                nums[left] = nums[right];
                nums[right] = t;
                left++;
                right--;
            }
        }
        
        if (start + (k - 1) <= right) {
            return quickSelect(nums, start, right, k);
        }
        if (start + (k - 1) >= left) {
            return quickSelect(nums, left, end, k - (left - start));
        }
        return nums[left - 1];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值