leetcode_215数组中第k大的值

215 数组中第k大的值
。

Java:

class Solution {
    public int findKthLargest(int[] nums, int k) {
        int left = 0, right = nums.length - 1;//变化左右缩小范围;
        while (true) {//注!!这里是true不是left<right,可以是left<=right
            int idx = quickSort(nums, left, right);//注!!根据返回下标缩小左右
            if (idx < nums.length - k) {
                left = ++idx;//注!!是根据index缩小左右
            }
            else if (idx > nums.length - k) {
                right = --idx;
            }
            else {
                return nums[idx];
            }
        }
    }
    int quickSort(int[] nums, int l, int r) {
        int cmp = nums[l];
        int left = l, right = r;
        while (left < right) {
            while (left < right && nums[right] >= cmp) {
                right--;//注!!选择左边基准值需要先从右边移动;
            }
            while (left < right && nums[left] <= cmp) {
                left++;
            }
            int tem = nums[left];
            nums[left] = nums[right];
            nums[right] = tem;
        }
        nums[l] = nums[left];
        nums[left] = cmp;
        return left;
    }
}

C++:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int left = 0, right = nums.size() - 1;
        while (true) {
            int res = quickSort(left, right, nums);
            if (res == nums.size() - k) {
                return nums[res];
            }    
            else if (res < nums.size() - k) {
                left = res + 1;
            }
            else {
                right = res - 1;
            }
        }
        return -1;
    }
private:
    
    int quickSort(int left, int right, vector<int> &nums) {
        int i = left, j = right, cmp = nums[left];
        while (i < j) {
            while (i < j && nums[j] >= cmp) {
                j--;
            }
            if (i < j) {
                nums[i] = nums[j];
                i++;
            }
            while (i < j && nums[i] <= cmp) {
                i++;
            }
            if (i < j) {
                nums[j] = nums[i];
                j--;
            }
        }
        nums[i] = cmp;
        return i;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值