zoukankan      html  css  js  c++  java
  • 最小的k个数

    题目描述

    输入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

    结束!

  • 相关阅读:
    HDU 4005 The war
    #undef
    [转载] #define new DEBUG_NEW
    [转载]常用正则表达式
    [百科]
    [转载]
    [转载]
    [转载]
    [百科]
    [转载]VC6中的文件后缀
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13815333.html
Copyright © 2011-2022 走看看