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.
Example 1:
题目描述:找到第 k 大的元素。
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
思路:快速排序定位法 因为要找k值 所以只需排k的部分
时间复杂度o(n)
定位思路最左边定义为一个哨兵,然后比k大的放左边,比k小的放右边
如果碰到相反的则交换
如果左边地址坐标大于等于右面 退出
然后交换哨兵与右边坐标位置 直到找到k-1位置为止
代码:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left=0,right=nums.size()-1;
while(left<right){
int j=partion(nums,left,right);
if(j==k-1)
break;
else if(j>k-1)
right=j-1;
else
left=j+1;
}
return nums[k-1];
}
int partion(vector<int>& nums,int left,int right){
int p=nums[left];
int l=left+1;
int r=right;
while(true){
while(nums[l]>=p&&l<right)l++;
while(nums[r]<=p&&r>=l)r--;
if(l>=r)break;
swap(nums[l],nums[r]);
}
swap(nums[left],nums[r]);
return r;
}
};