1. 题目

2. 思路和题解
这道题其实就是用昨天总结的常用排序算法里的快速排序。因为每次经过划分操作之后,一定是可以确定出一个元素的最终位置,因此我们不需要全部排序完成,只需要某次划分的 q q q为倒数第 k k k个下标的时候,就已经确定了答案。
java
class Solution {
int quickselect(int[] nums, int left, int right, int k) {
if (left == right) {
return nums[k];
}
int x = nums[left], i = left - 1, j = right + 1;
while (i < j) {
do i++; while (nums[i] < x);
do j--; while (nums[j] > x);
if (i < j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
if (k <= j) return quickselect(nums, left, j, k);
else return quickselect(nums, j + 1, right, k);
}
public int findKthLargest(int[] _nums, int k) {
int n = _nums.length;
return quickselect(_nums, 0, n - 1, n - k);
}
}