二分查找
方法一:手动实现二分
golang实现C++中upper_bound & lower_bound_go lowerbound
package main
import "fmt"
func LowerBound(st, ed int, key int, arr []int) int {
left, right := st, ed-1
for left < right {
mid := (left + right) >> 1
if arr[mid] >= key {
right = mid
} else {
left = mid + 1
}
}
return right
}
func UpperBound(st, ed int, key int, arr []int) int {
left, right := st, ed-1
for left < right {
mid := (left + right) >> 1
if arr[mid] > key {
right = mid
} else {
left = mid + 1
}
}
return right
}
func main() {
arr := []int{1, 2, 2, 2, 2, 2, 2, 2, 3, 4}
low := LowerBound(0, len(arr), 2, arr)
up := UpperBound(0, len(arr), 2, arr)
fmt.Println(low)
fmt.Println(up)
}