因为0<=val<=1000, 数组元素值较小。 故可以考虑用hashmap保存每个元素值出现的次数,然后从0到1000遍历所有值,把其加入返回的数组中
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param input int整型一维数组
# @param k int整型
# @return int整型一维数组
#
class Solution:
def GetLeastNumbers_Solution(self , input: List[int], k: int) -> List[int]:
# write code here
count={}
for n in input:
if n not in count:
count[n]=1
else:
count[n]+=1
res=[]
for i in range(1001):
if i in count:
res.extend([i]*count[i])
if len(res)>=k:
break
return res[:k]