Kth Largest Element
Source
Find K-th largest element in an array.
Example
In array [9,3,2,4,8], the 3rd largest element is 4.
In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4,
3rd largest element is 3 and etc.
Note
You can swap elements in the array
Challenge
O(n) time, O(1) extra memory.
Java
class Solution {
public int kthLargestElement(int k, int[] nums) {
return quickSelect(nums, 0, nums.length - 1, k);
}
private int quickSelect(int[] nums, int start, int end, int k) {
int pivot = end;
int left = start;
int right = end - 1;
while (left <= right) {
if (nums[left] > nums[pivot]) {
swap(nums, left, right);
right--;
} else {
left++;
}
}
swap(nums, left, pivot);
int rank = nums.length - left;
if (rank == k) return nums[left];
if (rank > k) return quickSelect(nums, left + 1, end, k);
return quickSelect(nums, start, left - 1, k);
}
private void swap(int[] nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
};