#include
#include
#include
/*
* 和快速排序一样:
* 第K小 [low,high)
* 1.找一个基准,找出其在整个序列data里面的绝对位置 s ,比data[s]大的都在右边,小的都在左边
* 2.如果K==S,则表示要求的数据就是S
* 3.如果K
S,在区间[s+1,high)之间找第k个
*
* */
void swap(int data[], int i, int j)
{
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
int partion(int data[], int low, int high)
{
int i = low, j = high - 1;
while (i < j)
{
while (data[j] >= data[i] && i < j)
j--;
if (i < j) { swap(data, i++, j); }
while (data[i] <= data[j] && i < j)
i++;
if (i < j) { swap(data, i, j--); }
}
return i ;// 在数组data中的绝对位置,且data[i] 在data中是第i大的,(i从0开始),比data[i]小的都在左边,比它大的都在右边
}
//第k大,k从0开始
int findKth(int data[], int k, int low, int high)
{
if (low + 1 >= high)
return data[low];
int s = partion(data, low, high);
if (k == s)return data[k];
if (k < s)
return findKth(data, k, low, s);//partion中j = high - 1,所以区间是[low,s) 不用s-1
return findKth(data, k , s+1 , high);//s+1 往上走一步,如果是s的话,可能s==low==0 一直在递归
}
void main()
{
int data[] = { 12, 11, 1, 13, 2, 10, 4, 9, 1, 8, 6, 18 };
printf("%d", findKth(data, 8, 0, sizeof(data) / sizeof(data[0]))); //求第9大的数
}
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 partion(vector<int>& nums,int start,int end){
int i=start;
int j=end;
while(i<j){
while(i<j&&nums[i]>=nums[j])
i++;
if(i<j)
swap(nums[i],nums[j]);
while(i<j&&nums[i]>=nums[j])
j--;
if(i<j)
swap(nums[i],nums[j]);
}
return i;
}
int findKthLargest(vector<int>& nums, int k) {
int start=0;
int end=nums.size()-1;
k--;
while(true){
int i=partion(nums,start,end);
if(i==k)
return nums[i];
else if(i<k)
start=i+1;
else
end=i-1;
}
}
};