Find the closest elements above and below a given number

前端 未结 4 1503
小鲜肉
小鲜肉 2020-12-15 00:47
myArr = array([4,1,88,44,3])
myNumber = 25
FindClosest(myArr, myNumber)
...
4, 44

Is there any way to find the closest 2 numbers in a list to a giv

4条回答
  •  没有蜡笔的小新
    2020-12-15 01:25

    Sorting is not necessary, and makes this time complexity O(n logn) when it should be just O(n).

    I believe this is what you're looking for, taking advantage of numpy array indexing:

    >>> # the smallest element of myArr greater than myNumber
    >>> myArr[myArr > myNumber].min()  
    44
    
    >>> # the largest element of myArr less than myNumber
    >>> myArr[myArr < myNumber].max()
    4
    

提交回复
热议问题