参见:

二分查找

90%以上的程序员无法正确无误地写出二分查找代码。—- Jon Bentley [Programming Pearls]

704. 二分查找

难度: 简单




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func binarySearch(nums []int, target int) int {
low := 0
high := len(nums) - 1
for low <= high {
middle := low + (high-low)/2
midValue := nums[middle]
if midValue == target {
return middle
} else if midValue > target {
high = middle - 1
} else {
low = middle + 1
}
}
return -1
}