时间限制:1秒
空间限制:32768K
热度指数:214405
算法知识视频讲解
题目描述
输入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) {
int t = input.size();
int x = 0;
for(int i = 0; i < t - 1; i ++)
{
for(int j = 0; j < t - i - 1; j ++)
{
if(input[j] > input[j + 1])
{
x = input[j];
input[j] = input[j + 1];
input[j + 1] = x;
}
}
}
vector <int> r;
if(k > t)
return r;
else
{
for(int i = 0; i < k; i ++)
{
r.push_back(input[i]);
}
return r;
}
}
};
python实现:
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
a = sorted(tinput)
b = []
if k > len(tinput):
return b
else:
b = a[0:k]
return b