剑指Offer(Python多种思路实现):最小的k个数

面试40题:

题目:最小的k个数

题:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

解题思路一:

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

解题思路二:

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)

解题思路三:

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)
发布了53 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44151089/article/details/104489871
今日推荐