所以你想找到 largest value less than or equal to currentTime 和 smallest value higher than or equal to 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.
1 回答
所以你想找到 largest value less than or equal to currentTime 和 smallest value higher than or equal to currentTime . 你的答案必须是其中之一 .
对于第一个,您可以像这样编写二进制搜索:
运行后,
store
将包含小于或等于target
的最后一个索引 . 然后你可以检查: