Prove safety offer: acquiring the minimum number of k

 

1 idea:

With a stored list of length k k-th smallest number, through the array, each to a number, this number will be and comparing the maximum number in the list, if less than the maximum number, then the maximum number of change out.

This idea is right, but can then optimized. Do list, but with a large root heap.

Large root heap definition:

        A full binary tree; root> left, right  

An array large root heap storage methods:

         for the root node of the index i is the index (i-1) // 2; index of its child nodes is about 2 * i + 1, 2 * i + 2

Construction of a large pile own root / root small heap:

# -*- coding:utf-8 -*-
import heapq
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        if k>len(tinput) or k==0:
            return []
        
        # 用前 k 个数构建大根堆
        maxh = []
        for num in tinput[:k]:
            heapq.heappush(maxh,-num)
        
        # 依次把数插入大根堆
        for num in tinput[k:]:
            if num < -maxh[0]:
                heapq.heapreplace(maxh,-num)
        for i in range(len(maxh)):
            maxh[i] = -maxh[i]
        maxh.sort()
        return maxh
    
    def swap(h,i,j):
        temp = h[i]
        h[i] = h[j]
        h[j] = temp
    j
    def buildMaxStack(stack,start,n): #根据stack构建大根堆,从i到j排序
        # n = len(stack)-1
        i = n//2-1
        while i >=0:
            if stack[i] > max([stack[2*i+1],stack[2*i+2]]):
                pass
            else:
                if max([stack[2*i+1],stack[2*i+2]]) == stack[2*i+1]:
                    self.swap[stack,2*i+1,i]
                    if 2*(2*i+1)+1 > n :
                        pass
                    
                
            i-=1
        
        
        
        

 

 

 

Published 82 original articles · won praise 2 · Views 4349

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104833631