题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
C++
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int>res;
int len = input.size();
if (len == 0 || k > len) return res;
Qsort(input, 0, len - 1); //快排
for (int i = 0; i < k; i++)
res.push_back(input[i]);
return res;
}
void Qsort(vector<int>&input, int left, int right)
{
int pivot; //中轴位置
if (left < right)
{
pivot = Partition(input, left, right); //算出中轴位置
//递归进行分割
Qsort(input, left, pivot - 1);
Qsort(input, pivot + 1, right);
}
}
int Partition(vector<int>&input, int left, int right)
{
int temp, pivotkey;
int i, j;
pivotkey = input[left]; //以第一个元素为中轴元素
i = left + 1;
j = right;
while (true) //从表的两端交替的向中间扫描
{
//向右找到第一个大于等于 pivotkey 的元素位置
while(i <= j && input[i] <= pivotkey)
i++;
//向左找到第一个小于等于 pivotkey 的元素位置
while (i <= j && input[j] >= pivotkey)
j--;
if (i >= j) break;
//交换,使得左边不大于pivotkey,右边不小于pivotkey
temp = input[j];
input[j] = input[i];
input[i] = temp;
}
input[left] = input[j];
input[j] = pivotkey;
return j;
}
};
Python
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
size = len(tinput)
res = []
if k > size:
return res
tinput.sort()
for i in range(k):
res.append(tinput[i])
return res