首页 > 其他 > 详细

最小的k个数

时间:2020-10-14 19:18:02      阅读:29      评论:0      收藏:0      [点我收藏+]

题目描述

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

解答

先排序,再返回最小的k个数

# coding:utf-8
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        for i in range(len(tinput)-1, 0, -1):
            for j in range(i):
                if tinput[j] > tinput[j+1]:
                    tinput[j], tinput[j+1] = tinput[j+1], tinput[j]
        if 0 < k <= len(tinput):
            return tinput[0:k]
        else:
            return []


p = Solution()
ret = p.GetLeastNumbers_Solution([2,1,3],3)
print ret

结束!

最小的k个数

原文:https://www.cnblogs.com/aaronthon/p/13815333.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!