利用快速排序分区方法,
深入理解
return findXth(nums+index+1, numsSize-index-1,x-index-1);
else
return findXth(nums, index, x);
int partition(int a[], int low, int high)
{
int pivot = a[low]; //挖坑
while(low < high){
for(;(low < high)&&(a[high] >= pivot); high--);
a[low] = a[high]; //找到第一个小于pivot的填坑
for(;(low < high)&&(a[low] <= pivot); low++);
a[high] = a[low];//找到第一个大于pivot的填坑
}
//low high相交的时候,把low填入pivot,通知返回low坐标,low代表在排序数组中的下坐标 ,第low+1个
a[low] = pivot;
return low;
}
int findXth(int* nums, int numsSize, int x) {
int index;
index = partition(nums, 0, numsSize-1);
if(index == x)
return nums[index];
if(index < x)
return findXth(nums+index+1, numsSize-index-1,x-index-1);
else
return findXth(nums, index, x);
}
int findKthLargest(int* nums, int numsSize, int k) {
return findXth(nums, numsSize, numsSize-k);
}
网友评论