Find the
k
th 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.
class Solution {
public:
int partition(vector<int>& nums, int start, int end)
{
if(nums.size()==0 || start>end )
return -1;
int tmp = nums[start];
while(start<end)
{
while(start<end&&nums[end]<=tmp)
end--;
nums[start] = nums[end];
while(start<end&&nums[start]>=tmp)
start++;
nums[end] = nums[start];
}
nums[start] = tmp;
return start;
}
int findKthLargest(vector<int>& nums, int k) {
if(nums.size()==0 || k == 0 || k > nums.size() )
return -1;
int start = 0;
int end = nums.size()-1;
int index = partition(nums, start, end);
while(index!=k-1)
{
if(index>k-1)
{
end = index-1;
index = partition(nums, start, end);
}else if(index<k-1)
{
start = index+1;
index = partition(nums, start, end);
}
}
return nums[index];
}
};