题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
解答
先排序,再返回最小的k个数
# coding:utf-8
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
for i in range(len(tinput)-1, 0, -1):
for j in range(i):
if tinput[j] > tinput[j+1]:
tinput[j], tinput[j+1] = tinput[j+1], tinput[j]
if 0 < k <= len(tinput):
return tinput[0:k]
else:
return []
p = Solution()
ret = p.GetLeastNumbers_Solution([2,1,3],3)
print ret
结束!