Find the x smallest integers in a list of length n

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

    In scala, and probably other functional languages, a no brainer:

    scala> List (1, 3, 6, 4, 5, 1, 2, 9, 4)  sortWith ( _<_ ) take 5
    res18: List[Int] = List(1, 1, 2, 3, 4)
    

提交回复
热议问题