[剑指offer] 最小的K个数

题目内容

https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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


题目思路

找出最小的K个数,也就是找到前K个最小的数值。我觉得可以考虑使用排序然后返回前K个即可。当然也可以只选出前K个,然后排序,这样的效率会更高一些。


程序代码

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        lgt=len(tinput)
        if lgt<k or k==0:
            return []
        res=[tinput[0]]
        for i in tinput:
            if len(res)<k:
                if i not in res:
                    res.append(i)
            elif i>=max(res):
                pass 
            else:
                res.remove(max(res))
                res.append(i)
        return sorted(res)
                
        
# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        lgt=len(tinput)
        if lgt<k:
            return []
        tinput.sort()
        return tinput[:k]
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值