題目描述
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4。
方法:
用最大堆實現,先建立一個k大堆,然後不斷比較維護一個k大堆。最後再運用K大堆對k個樹從小到大排列輸出。
class Solution:
def duipai(self,i,HeapList,ListLen):
HeapList[0] = HeapList[i]
j = i*2
while(j <= ListLen):
if j < ListLen and HeapList[j] < HeapList[j+1]:
j = j+1
if HeapList[0] >= HeapList[j]:
break
HeapList[i] = HeapList[j]
i = j
j = j*2
HeapList[i] = HeapList[0]
def GetLeastNumbers_Solution(self, tinput,k):
# write code here
if len(tinput) < k or k == 0:
return []
'''取前K個數進行堆排'''
list2 = tinput[0:k]
list2 = [0] + list2
for i in range(k // 2,0,-1):
self.duipai(i,list2,k)
'''從第k+1個數開始與堆頂比較'''
for value in tinput[k:]:
if value < list2[1]:
list2[1] = value
self.duipai(1,list2,k)
'''最後K個值堆排實現從小到大排列'''
for m in range(k,1,-1):
list2[m],list2[1] = list2[1],list2[m]
self.duipai(1,list2,m -1)
return list2[1:]