繁体   English   中英

二进制搜索最接近的索引/索引与O(log n)的值

[英]binary search for closest index/ index's to a value with O(log n)

我已经对对象的数组(可能存在重复项)进行了排序,其中dateTime以毫秒为对象的成员,我想获取与currentTime的dateTime差异最小的数组的索引/索引。 我想到了使用二进制搜索,但是它需要键存在于数组中。 我可以使用简单的for循环,但是它将是O(n),是否有一个有效的二进制搜索变量来获得具有O(log n)效率的索引/索引?

我想获取与currentTime的dateTime差异最小的数组的索引/索引

所以,你要找到最大值小于或等于currentTime高于最小值或等于currentTime 您的答案必须是其中之一。

对于第一个,您可以这样编写二进制搜索:

while left < right:
  m = left + (right - left) / 2
  if array[m] <= target: # using <= here to save the right index 
                         # in store in case the key exists
    left = m + 1
    store = m
  else:
    right = m

运行之后, store将包含小于或等于target的最后一个索引。 然后您可以检查:

if array[store] == target:
  you found the target exactly
else:
  check array[store] and array[store + 1] (if not out of bounds) and pick the best.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM