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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return partition(nums,0,nums.size()-1,k);
}
int partition(vector<int> & nums,int low,int high,int k)
{
int key = nums[low];
int l = low;
int h = high;
while (l < h)
{
while(l < h && nums[h] <= key) --h;
nums[l] = nums[h];
while(l < h && nums[l] >= key) ++l;
nums[h] = nums[l];
}
nums[l] = key;
if (k == l+1) return nums[l];
else if (k > l+1) return partition(nums,l+1,high,k);
else return partition(nums,low,l-1,k);
}
};
利用快速排序paratition操作,将标定点key放置在正确位置上的性质,当key==k,即找到了该数组中第k大的元素。