算法通关村第十关|白银|数组中第K大的数字

数组中第K大的数字

原题:力扣215

这里使用快速排序来解决问题,同时因为哨兵位的索引是已知的,所以可以通过索引知道第K大的数字在左侧还是右侧,可以避免另一部分的排序。

int quickselect(int[] nums, int l, int r, int k) {
	if (l == r) {
        return nums[k];
    }
    int x = nums[l], i = l - 1, j = r + 1;
    while (i < j) {
        do {
            i++;
        } while (nums[i] < x);
        do {
            j--;
        } while (nums[j] > x);
        if (i < j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
    if (k <= j) {
        return quickselect(nums, l, j, k);
    } else {
        return quickselect(nums, j + 1, r, k);
    }
}

public int findKthLargest(int[] nums, int k) {
	int n = nums.length;
    return quickselect(nums, 0, n - 1, n - k);
}

如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤
个人主页:星不易 ❤
算法通关村专栏:不易|算法通关村 ❤

你可能感兴趣的:(不易,算法通关村,算法,java,算法通关村)