The minimum number of K Python

Input n integers, find the smallest number K. 4,5,1,6,2,7,3,8 e.g. eight digital inputs, the minimum number is four 1,2,3,4

Find the time complexity of the largest heap of O (logK)
replace complexity is also O (logK)
for spatial array of complexity is O (K)

If change is to solve the problem with the array, then
find the time complexity is O (logK) (using binary search)
the complexity of the replacement of O (K)
complex array of auxiliary space is O (K)

The main difference between the two programs is that the complexity of the replacement, so a maximum heap solve the problem. Encountered a similar situation, the smallest stack has the same advantages.

# -*-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])

Operating results as follows:

1
2
4
6
Published 135 original articles · won praise 121 · Views 4856

Guess you like

Origin blog.csdn.net/weixin_44208324/article/details/105316529