美文网首页
最小的K个数

最小的K个数

作者: GoDeep | 来源:发表于2018-04-04 20:31 被阅读0次

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

    # -*- coding:utf-8 -*-
    import heapq
    class Solution:
        def GetLeastNumbers_Solution(self, tinput, k):
            # write code here
            if k>len(tinput): return []
            pq = []
            for i in tinput:
                heapq.heappush(pq, -i)
                if len(pq)>k: heapq.heappop(pq)
            return sorted([-v for v in pq])
        
            
    

    相关文章

      网友评论

          本文标题:最小的K个数

          本文链接:https://www.haomeiwen.com/subject/hhylhftx.html