Leetcode-215-Kth Largest Element in an Array
Leetcode-215-Kth Largest Element in an Array
215. Kth Largest Element in an Array
Description Submission Solutions Add to List
- Total Accepted: 109821
- Total Submissions: 290143
- Difficulty: Medium
- Contributors: Admin
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.
Subscribe to see which companies asked this question.
Show Similar Problems
Have you met this question in a real interview?
题解:
(1),二分的用法,真的是哪里用都很奇妙
class Solution {
public:
int QuickSearch(vector<int>& nums, int k, int left, int right){
int lf = left, rg = right, midval = nums[left + (right-left)/2];
while(lf <= rg){
if(nums[lf] > midval){
lf++;
}else if(nums[rg] < midval){
rg--;
}else{
swap(nums, lf, rg);
lf++;
rg--;
}
}
if(lf < right && lf <= k){
return QuickSearch(nums, k, lf, right);
}
if(rg > left && rg >= k){
return QuickSearch(nums, k, left, rg);
}
return nums[k];
}
void swap(vector<int>& nums, int a, int b){
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
int findKthLargest(vector<int>& nums, int k) {
return QuickSearch(nums, k-1, 0, nums.size()-1);
}
};

浙公网安备 33010602011771号