且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何有效地在大型排序数组中找到最接近另一个值 X 的值

更新时间:2023-08-29 12:04:22

您可以使用 bisect 模块:

You can use the bisect module:

import bisect

data = [37, 72, 235, 645, 715, 767, 847, 905, 908, 960]

location = bisect.bisect_left(data, 700)

result = data[location - 1]

这是标准库中的一个模块,它将使用二进制搜索来查找所需的结果.根据您需要的确切值,您还可以使用 bisect_right 而不是 bisect_left.

This is a module in the standard library which will use binary search to find the desired result. Depending on the exact value that you need you can also use bisect_right instead of bisect_left.

这比遍历列表更快,因为二分搜索算法可以跳过不包含答案的部分数据.这使得它非常适合在已知数据已排序的情况下寻找最接近的数字.

This is faster than iterating over the list because the binary search algorithm can skip parts of the data that won't contain the answer. This makes it very suitable for finding the nearest number when the data is known to be sorted.