思路
借助快排的Partition函数
注意:
1、是第K大,因此Partition返回的结果要和n-K比较!!!
代码
class Solution {
public:
int Partition(vector<int>& arr, int L, int R ){
int right = R;
int left = L;
int key = arr[left];
while(left< right){
while(left< right && arr[right]>=key){
right--;
}
arr[left] = arr[right];
while(left< right && arr[left]<=key){
left++;
}
arr[right] = arr[left];
}
arr[left] = key;
return left;
}
int findKth(vector<int> a, int n, int K) {
// write code here
int start = 0;
int end = n-1;
int index = Partition(a, start, end);
while(index!=n-K){
if(index<n-K){
start = index+1;
index = Partition(a, start, end);
}
else{
end = index-1;
index = Partition(a,start, end);
}
}
return a[index];
}
}; 
京公网安备 11010502036488号