记录二分查找模板(GO语言),寻找升序切片中是否含有元素target。
如果切片中存在target,返回该元素的index;
如果切片中不存在target,返回该元素应该插入的index;
func mySearchInts(slices []int, target int) int {
i, j := 0, len(slices)
for i < j {
h := i + (j-i)/2 // avoid overflow when computing h
if slices[h] < target {
i = h + 1
} else {
j = h
}
}
return i
}
降序切片只需要更改判断条件:
func mySearchInts(slices []int, target int) int {
i, j := 0, len(slices)
for i < j {
h := i + (j-i)/2 // avoid overflow when computing h
if slices[h] > target {
i = h + 1
} else {
j = h
}
}
return i
}