最小的K个数,输入N个数,找出最小的K个数
解法一:先排序再数数O(NlogN)
解法二:用最大堆来保存数据,直至遍历完毕,
解法三:用快速排序法找出第K位位置,K位左侧既是最小的K个数
解法一:
void quickSort(int* input,int len, int start, int end)
{
if (start < 0 || end < 0 || start >= len || end >= len || start >= end) return;
int l = start + 1;
int h = end;
while (l<=h)
{
while (h>start && input[h]> input[start]) h--;
while (l < h && input[l] <= input[start]) l++;
if (l<h)
{
int temp = input[l];
input[l] = input[h];
input[h] = temp;
}
else
break;
}
if (h>start)
{
int temp = input[start];
input[start] = input[h];
input[h] = temp;
}
quickSort(input, len, start, h - 1);
quickSort(input, len, h + 1, end);
}
void GetLeastNumbers_Solution3(int* input, int n, int* output, int k)
{
if (input == nullptr || n <= 0 || output == nullptr || k <= 0 || k > n) return;
int* sortArray = new int[n]();
for (int i = 0; i < n; i++)
sortArray[i] = input[i];
quickSort(sortArray, n, 0, n - 1);
for (int i = 0; i < k;i++)
output[i] = sortArray[i];
return;
}
解法二:
void GetLeastNumbers_Solution4(int* input, int n, int* output, int k)//diy heap
{
if (input == nullptr || n <= 0 || output == nullptr || k <= 0 || k>n) return;
std::priority_queue<int> smallHeap;
for (int i=0;i<n;i++)
{
if (smallHeap.size()<k)
smallHeap.push(input[i]);
else if (smallHeap.size()>=k && input[i]<=smallHeap.top())
{
smallHeap.pop();
smallHeap.push(input[i]);
}
}
for (int i=0;i<k;i++)
{
(output)[i] = smallHeap.top();
smallHeap.pop();
}
}
解法3:在1的基础上改了一下
void findKNum(int* input, int len,int k, int start, int end)//diy
{
if (start > k) return;
int l = start + 1;
int h = end;
while (l <= h)
{
while (h>start && input[h]> input[start]) h--;
while (l < h && input[l] <= input[start]) l++;
if (l<h)
{
int temp = input[l];
input[l] = input[h];
input[h] = temp;
}
else
break;
}
if (h>start)
{
int temp = input[start];
input[start] = input[h];
input[h] = temp;
}
if (h == k)
return;
else if (h<k)
return findKNum(input, len, k, h + 1, end);
else
return findKNum(input, len, k, start, h - 1);
}
void GetLeastNumbers_Solution4(int* input, int n, int* output, int k)//diy
{
if (input == nullptr || n <= 0 || output == nullptr || k <= 0 || k > n) return;
int* sortArray = new int[n]();
for (int i = 0; i < n; i++)
sortArray[i] = input[i];
findKNum(sortArray, n, k-1, 0, n - 1);
for (int i = 0; i < k; i++)
output[i] = sortArray[i];
return;
}