输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
基本思路:建立一个包含K个元素的大顶堆。
注:python中貌似只能直接建小顶堆。
# -*- coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
# write code here
if k <= 0 or k > len(tinput):
return []
import heapq
heap = [-item for item in tinput[:k]]
heapq.heapify(heap)
for i in range(k, len(tinput)):
if -tinput[i] > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, -tinput[i])
heap = [-item for item in heap]
return sorted(heap)