KのPythonの最小数

入力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
公開された135元の記事 ウォンの賞賛121 ビュー4856

おすすめ

転載: blog.csdn.net/weixin_44208324/article/details/105316529