输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4
最大堆的查找时间复杂度为O(logK)
替换的复杂度也为O(logK)
辅助数组的空间复杂度为O(K)
如果换为用数组解决该问题,那么
查找的时间复杂度为O(logK)(采用折半查找)
替换的复杂度为O(K)
辅助数组的空间复杂度为O(K)
两种方案的主要区别在于替换的复杂度,因此采用最大堆解决该问题。遇到类似的情况时,最小堆也有同样的优势。
# -*-coding:utf-8 -*-
class Solution:
def GetLeastNumbers_Solutions(self, tinput, k):
# 创建或者是插入最大堆
def createMaxHeap(num):
maxHeap.append(num)
currentIndex = len(maxHeap) - 1
while currentIndex != 0:
parentIndex = (currentIndex - 1) >> 1
if maxHeap[parentIndex] < maxHeap[currentIndex]:
maxHeap[parentIndex], maxHeap[currentIndex] = maxHeap[currentIndex], maxHeap[parentIndex]
else:
break
# 调整最大堆,头节点发生改变
def adjustMaxHeap(num):
if num < maxHeap[0]:
maxHeap[0] = num
maxHeapLen = len(maxHeap)
index = 0
while index < maxHeapLen:
leftIndex = index * 2 + 1
rightIndex = index * 2 + 2
largerIndex = 0
if rightIndex < maxHeapLen:
if maxHeap[rightIndex] < maxHeap[leftIndex]:
largerIndex = leftIndex
else:
largerIndex = rightIndex
elif leftIndex < maxHeapLen:
largerIndex = leftIndex
else:
break
if maxHeap[index] < maxHeap[largerIndex]:
maxHeap[index], maxHeap[largerIndex] = maxHeap[largerIndex], maxHeap[index]
index = largerIndex
maxHeap = []
inputLen = len(tinput)
if len(tinput) < k or k <= 0:
return []
for i in range(inputLen):
if i < k:
createMaxHeap(tinput[i])
else:
adjustMaxHeap(tinput[i])
maxHeap.sort()
return maxHeap
if __name__ == '__main__':
tinput=[1,2,4,6,100,20,9,10]
s=Solution()
result = s.GetLeastNumbers_Solutions(tinput,4)
for i in range(0,4):
print(result[i])
运行结果为:
1
2
4
6