一、題目描述
輸入n個整數(shù),找出其中最小的K個數(shù)。例如輸入4,5,1,6,2,7,3,8這8個數(shù)字,則最小的4個數(shù)字是1,2,3,4。
二、代碼實(shí)現(xiàn)
# -*- 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