LeetCode 215. Kth Largest Element in an Array
Description
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
public class Solution {
public int findKthLargest(int[] nums, int k) {
int index = quickSelect(nums, 0, nums.length-1, k-1);
return nums[index];
}
private int quickSelect(int[] nums, int lo, int hi, int k) {
int lt = lo;
int gt = hi + 1;
int i = lo + 1;
int pivot = nums[lo];
while (i < gt) {
if (nums[i] > pivot) {
swap(nums, i, lt + 1);
lt++;
i++;
}
else if (nums[i] < pivot) {
swap(nums, i, gt - 1);
gt--;
}
else {
i++;
}
}
swap(nums, lo, lt);
if (lt == k) {
return lt;
}
else if (lt < k) {
return quickSelect(nums, lt + 1, hi, k);
}
else {
return quickSelect(nums, lo, lt - 1, k);
}
}
private void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Complexity analysis
Time complexity : O(n).
Space complexity : O(log(n