题目内容
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
题目思路
找出最小的K个数,也就是找到前K个最小的数值。我觉得可以考虑使用排序然后返回前K个即可。当然也可以只选出前K个,然后排序,这样的效率会更高一些。
程序代码
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
lgt=len(tinput)
if lgt<k or k==0:
return []
res=[tinput[0]]
for i in tinput:
if len(res)<k:
if i not in res:
res.append(i)
elif i>=max(res):
pass
else:
res.remove(max(res))
res.append(i)
return sorted(res)
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
lgt=len(tinput)
if lgt<k:
return []
tinput.sort()
return tinput[:k]