go快排计算最小k个数和第k大的数
计算最小的k个数,除了用堆,还可以用快排
每次返回left right相遇的位置,index>k 则向左搜,index<k 向右搜,直到index==k
剑指40 最小k个数(没要求顺序)
- golang快排
func getLeastNumbers(arr []int, k int) []int {
if k==0{
return []int{}
}
index:=Fast(arr,0,len(arr)-1,k)
for index!=k-1{
if index>k-1{
index = Fast(arr,0,index-1,k)
}else{
index = Fast(arr,index+1,len(arr)-1,k)
}
}
res:=make([]int,index+1)
copy(res,arr[:index+1])
return res
}
func Fast(nums []int,low,high,k int)int {
start:=low
end:=high
tmp:=nums[low]
for start<end{
for start<end&&nums[end]>=tmp{
end--
}
nums[start] = nums[end]
for start<end&&nums[start]<=tmp{
start++
}
nums[end] = nums[start]
}
nums[start] = tmp
return start
}
- c++版本
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if(input.size()<k||k==0) return {};
int index = fast(input,0,input.size()-1);
while(index!=k-1)
{
if(index>k-1)
index = fast(input,0,index-1);
else
index = fast(input,index+1,input.size()-1);
}
return vector<int>(input.begin(),input.begin()+k);
}
int fast(vector<int>&arr,int low,int high)
{
if(low>=high)return low;
int start = low;
int end = high;
int tmp = arr[low];
while(start<end)
{
while(start<end&&arr[end]>=tmp) end--;
arr[start] = arr[end];
while(start<end&&arr[start]<=tmp) start++;
arr[end] = arr[start];
}
arr[start] = tmp;
return start;
}
leetcode 215 第k个最大元素
func findKthLargest(nums []int, k int) int {
return Fast(nums,0,len(nums)-1,k)
}
func Fast(nums []int,low,high,k int)int {
start:=low
end:=high
tmp:=nums[low]
for start<end{
for start<end&&nums[end]<=tmp{
end--
}
nums[start] = nums[end]
for start<end&&nums[start]>=tmp{
start++
}
nums[end] = nums[start]
}
nums[start] = tmp
if start==k-1{
return nums[k-1]
}else if start>k-1{
return Fast(nums,low,start-1,k)
}else{
return Fast(nums,start+1,high,k)
}
}