《苦练算法》

题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

题目分析
就是排序+数组取值,比较简单,直接上代码

1
2
3
4
5
6
7
8
9
10
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if not tinput:
return []
if k>len(tinput):
return []
t = sorted(tinput)
return t[:k]