215. 数组中的第K个最大元素

该博客介绍了如何使用修改版的快速排序算法来找到数组中的第K个最大元素。通过引入随机化选择枢轴元素的方法,提高了在最坏情况下的效率。算法包括随机选择、快速排序和分区操作,实现了在平均情况下线性时间复杂度的查找过程。

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

215. 数组中的第K个最大元素

class Solution {
    Random random = new Random();
    public int findKthLargest(int[] nums, int k) {
        return quicksort(nums,0,nums.length - 1,nums.length - k);
    }
    public int quicksort(int[] nums,int l, int r,int k){
        int q = randomSelect(nums,l,r);
        if(q == k) return nums[q];
        else{
           return q > k ? quicksort(nums,l,q - 1,k):quicksort(nums,q + 1,r,k);
        }
    }

    public int randomSelect(int[] nums,int l, int r){
        int i = random.nextInt(r - l + 1) + l;
        swap(nums,i,r);
        return partition(nums,l,r);
    }
    public int partition(int[] nums,int l, int r){
        int x = nums[r];
        int i = l - 1;
        for(int j = l; j < r;j++){
            if(nums[j] <= x){
                swap(nums,++i,j);
            }
        }
        swap(nums,i + 1,r);
        return i + 1;
    }
    public void swap(int[] nums,int l, int r){
        int tmp = nums[l];
        nums[l] = nums[r];
        nums[r] = tmp;
    }
}

快排的修改版,肥肠好用,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值