Python 最小的K個數

輸入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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章