class Solution {
public int kthLargestElement(int k, int[] nums) {
int target = nums.length - k;
int i = 0, lo = 0, hi = nums.length-1;
while (true) {
i = partition(lo, hi, nums);
if (target < i) {
hi = i - 1;
} else if (target > i) {
lo = i + 1;
} else {
break;
}
}
return nums[i];
}
// quick select returns index i which nums[i] is i+1th smallest element in the array
// therefore if i == length-k means we found the kth largest element in the array
private static int partition(int lo, int hi, int[] nums) {
int pivot = nums[lo];
while (lo < hi) {
// from right to left, find the first element which is <= than pivot
while (lo<hi && nums[hi]>pivot) {
hi--;
}
nums[lo] = nums[hi];
// from left to right, find the first element which is > than pivot
while (lo<hi && nums[lo]<=pivot) {
lo++;
}
nums[hi] = nums[lo];
}
nums[lo] = pivot;
return lo;
}
}
Leetocde 215. Kth Largest Element in an Array
最新推荐文章于 2022-07-02 13:48:51 发布