一、题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
二、代码实现
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k > len(tinput): return []
import heapq
max_heap = []
for val in tinput:
val = -val
if len(max_heap) < k:
heapq.heappush(max_heap, val)
else:
heapq.heappushpop(max_heap, val)
res = sorted([-max_heap[i] for i in range(len(max_heap))])
return res
网友评论