题目描述
给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
题解
利用快排解决,快速排序每次都是找到一个数的正确位置,如果这个位置等于nums.length - k
(第k大的数),则就是结果。
class Solution {
int res = 0;
public int findKthLargest(int[] nums, int k) {
//第K大的数,目标下标为nums.length - k
int target = nums.length - k;
quickSort(nums, 0, nums.length - 1, target);
return res;
}
public void quickSort(int[] nums, int left, int right, int k){
if (left > right) return;
int l = left, r = right;
int tmp = nums[l];
while (l < r){
while (l < r && nums[r] >= tmp) r--;
while (l < r && nums[l] <= tmp) l++;
if (l < r){
int x = nums[l];
nums[l] = nums[r];
nums[r] = x;
}
}
if (l == k){
res = tmp;
return;
}else{
nums[left] = nums[l];
nums[l] = tmp;
if (l < k){
quickSort(nums, l + 1, right, k);
}else{
quickSort(nums, left, l - 1, k);
}
}
}
}