Find the x smallest integers in a list of length n

前端 未结 12 1785
时光取名叫无心
时光取名叫无心 2021-02-02 01:00

You have a list of n integers and you want the x smallest. For example,

x_smallest([1, 2, 5, 4, 3], 3) should return [1, 2, 3].

I\'ll v

12条回答
  •  悲&欢浪女
    2021-02-02 01:23

    def x_smallest(items, x):
        result = sorted(items[:x])
        for i in items[x:]:
            if i < result[-1]:
                result[-1] = i
                j = x - 1
                while j > 0 and result[j] < result[j-1]:
                    result[j-1], result[j] = result[j], result[j-1]
                    j -= 1
        return result
    

    Worst case is O(x*n), but will typically be closer to O(n).

提交回复
热议问题