1.题目要求:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
2.题目分析:
首先新建空列表,然后从大到小添加K个不同的数字,然后再向列表添加时要更新列表,比列表最后一个值大的不添加,比列表最后一个值小的要将最后一个值删除并将此数添加到合适的位置。
3.python实现:
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k>len(tinput) or k==0:#代码鲁棒性(排除特殊情况)
return []
result=[tinput[0]]#首先将所给数组中第一个数给辅助列表result
i=1
while i<len(tinput):#遍历所有数字
if len(result)<k:#先添加k个从小到大排列的数字
result.append(tinput[i])
m=len(result)-1
if result[m]<result[m-1]:#排序
while m>0:
if result[m-1]>result[m]:
result[m],result[m-1]=result[m-1],result[m]
m-=1
else:
if tinput[i] not in result:#添加k个后需要更新列表
n=k-1
if tinput[i]<result[n]:#如果新来的数字小于result中最后一个数
result[n]=tinput[i]
while n > 0:#重新排序
if result[n - 1] > result[n]:
result[n], result[n - 1] = result[n - 1], result[n]
else:
break
n -= 1
i+=1
return result