【数组与排序】数组中第k大的元素
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
代码
class Solution {
public:
int partition(vector<int>& nums, int l,int r){
int temp = nums[l];
while(l < r){
int temp = nums[l];
while(l < r){
while(l < r && nums[r] <= temp) r--;
swap(nums[l],nums[r]);
while(l < r && nums[l] >= temp) l++;
swap(nums[l],nums[r]);
}
}
nums[l] = temp;
return l;
}
int search(vector<int>& nums,int l,int r,int k){
int m =partition(nums,l,r);
if(m == k-1) return nums[m];
else if(m > k-1) return search(nums,l,m-1,k);
else return search(nums,m+1,r,k);
}
int findKthLargest(vector<int>& nums, int k) {
int length = nums.size();
if(k > length) return 0;
else return search(nums,0,length-1,k);
}
};