Find the x smallest integers in a list of length n

前端 未结 12 1783
时光取名叫无心
时光取名叫无心 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:19

    If the range of numbers (L) is known, you can do a modified counting sort.

    given L, x, input[]
    counts <- array[0..L]
    for each number in input
        increment counts[number]
    next
    
    #populate the output
    index <- 0
    xIndex <- 0
    while xIndex < x and index <= L
       if counts[index] > 0 then
           decrement counts[index]
           output[xIndex] = index
           increment xIndex
       else
           increment index
       end if
    loop
    

    This has a runtime of O(n + L) (with memory overhead of O(L)) which makes it pretty attractive if the range is small (L < n log n).

提交回复
热议问题