Problem
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.
Solution
1. 维护一个大小为K的最小堆,每次和堆的最小值比较
2. 用quick sort 的变形
class Solution {
int findHelper( vector<int>& nums, int k, int left, int right){
if(left > right) return INT_MIN;
int leftCopy = left, rightCopy = right;
int pivot = nums[left++];
while(left <= right){
if(nums[left] > pivot){
left++; continue;
}
if(nums[right] <= pivot){
right--; continue;
}
swap(nums[left++], nums[right--]);
}
swap(nums[leftCopy], nums[right]);
if(right == k-1) return nums[right];
if(right < k-1) return findHelper(nums, k, right+1, rightCopy);
else return findHelper(nums, k, leftCopy, right-1);
}
public:
int findKthLargest(vector<int>& nums, int k) {
return findHelper(nums, k, 0, nums.size()-1);
}
};