40 is inscribed: Minimum (large) number of K

Offer40 prove safety problem, and this was also a high incidence of interview topics

2019.4 ants gold dress and asked: find the number of pre-K 1000 million data in.

Ideas:

1. Direct the sorting algorithm, and then we can take the first K rows of good order. However, consider a single fast discharge time complexity is also O (nlog (n)). This time we have to sort all the data, obviously with the increasing amount of data, but also the complexity of the surge.

2. using the time complexity is O (n), we can consider this case did before seeking large numbers of K. Introduced partition function.

3. The offer provided to prove safety on an idea: to create a container of size K, the k original data into them, each of the remaining data is compared with the maximum value of K in the vessel, if the vessel is less than the maximum exchanged. Data that this binary tree container under test, the maximum value obtained by the maximum stack.

This problem application heap sort algorithm complexity is only O (nlog k), the heap is a complete binary tree, the biggest heap is the number of the top is the biggest; the method based on binary tree or heap to achieve, first of all before the array of k digital construct a maximum heap, and then from traversing k + 1 digital array, if less than the number of elements traversed to the top of the heap, so long will swap two numbers, reconstructed pile, continue the walk, the last remaining heap is the minimum number k, the time complexity is O (nlog k).

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        import heapq
        if tinput==None or len(tinput)<k or len(tinput)<0 or k<=0:
            return []
        
        return heapq.nsmallest(k,tinput)

  

Guess you like

Origin www.cnblogs.com/ivyharding/p/11216099.html