查找给定数字上下的最接近元素 [英] Find the closest elements above and below a given number
本文介绍了查找给定数字上下的最接近元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
myArr = array([4,1,88,44,3])
myNumber = 25
FindClosest(myArr, myNumber)
...
4, 44
有什么方法可以找到列表中与给定数字最接近的2个数字,以使其中一个较高而另一个较低?
Is there any way to find the closest 2 numbers in a list to a given number such that one of them is higher and the other lower?
我可以通过以下方式找到最接近的号码:
I can find the closest number by:
min(myArr.tolist(), key=lambda x:abs(x-myNumber))
推荐答案
排序不是必需的,并且使此时间复杂度为O(n logn),而它应该仅为O(n).
Sorting is not necessary, and makes this time complexity O(n logn) when it should be just O(n).
我相信这就是您要寻找的东西,可以利用numpy数组索引:
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
这篇关于查找给定数字上下的最接近元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文