Wins the Offer (Python idea implemented more): the minimum number of k

Interview 40 questions:

Title: smallest number k

Title: 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 ,.

A problem-solving ideas:

class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        if k >len(tinput):
            return []
        tinput.sort()
        return tinput[:k]

Problem-solving ideas II:

class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        import heapq
        #此方法时间复杂度为O(nlogk)
        if k >len(tinput):
            return []
        return heapq.nsmallest(k,tinput)

Problem-solving ideas three:

def GetLeastNumbers_Solution(self, tinput, k):
    import heapq as hq
    if k > len(tinput) or k <= 0: return []
    heap = [-x for x in tinput[:k]]
    hq.heapify(heap)
    for num in tinput[k:]:
        if -heap[0] > num:
            hq.heapreplace(heap, -num)
    return sorted(-x for x in heap)

 

Published 53 original articles · won praise 3 · views 20000 +

Guess you like

Origin blog.csdn.net/weixin_44151089/article/details/104489871