二分查找的前提
- 目标函数单调性(单调递增或者递减)
- 存在上下界(bounded)
- 能够通过索引访问(index accessible)
代码模版
left, right = 0, len(array) - 1
while left <= right:
mid = (left + right) / 2
if array[mid] == target:
# find the target!!
break or return result
elif array[mid] < target:
left = mid + 1
else:
right = mid - 1
示例
在递增数组里[10, 14, 19, 26, 27, 31, 33, 35, 42, 44] ,查找:31
二分查找代码模板
https://shimo.im/docs/hjQqRQkGgwd9g36J/read
Fast InvSqrt() 扩展阅读
https://www.beyond3d.com/content/articles/8/
实战题目
- https://leetcode-cn.com/problems/sqrtx/
- https://www.beyond3d.com/content/articles/8/ (扩展阅读)
- https://leetcode.com-cn/problems/valid-perfect-square/