(未处理)剑指offer 第29题 最小的K个数

题目描述:

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

思路1:

用堆排序

代码1.1:

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)

代码1.2(不调用包):

class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        # 用大根堆
        if len(tinput) < k:
            return []
        for i in range(1, k):
            tinput = self.build_heap(tinput, i)
        for j in range(len(tinput)):
            if tinput[j] < tinput[0]:
                tinput = self.heapify(tinput, j, k)
        return sorted(tinput[:k])
    def build_heap(self, l, i):
        cur = i
        while cur > 0:
            father = (cur - 1) // 2
            if l[cur] > l[father]:
                l[cur], l[father] = l[father], l[cur]
                cur = father
            else:
                break
        return l

    def heapify(self, l, j, k):
        l[0], l[j] = l[j], l[0]
        cur = 0
        left = 1
        while left < k:
            right = left + 1
            if right < k:
                if l[left] > l[right]:
                    max_lr = left
                else:
                    max_lr = right
            else:
                max_lr = left
            if l[cur] < l[max_lr]:
                l[cur], l[max_lr] = l[max_lr], l[cur]
                cur = max_lr
                left = cur * 2 + 1
            else:
                break
        return l

思路2:

用快排的思想做

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值