【AcWing】【Go】789. 数的范围
AcWing 789. 数的范围
这是一道二分的模板题,来自于AcWing,使用Go语言重新实现一遍C++中二分查找算法的模板,代码如下:
package main
import "fmt"
func main() {
var n, k int
fmt.Scanf("%d %d", &n, &k)
q := make([]int, n)
for i := 1; i <= n; i++ {
fmt.Scanf("%d", &q[i])
}
for i := 1; i <= k; i++ {
var x int
fmt.Scanf("%d", &x)
l, r := 1, n
for l < r {
mid := (l + r) >> 1
if q[mid] >= x {
r = mid
} else {
l = mid + 1
}
}
if q[l] == x {
fmt.Printf("%d ", l)
} else {
fmt.Printf("-1 -1\n")
continue
}
l, r = 1, n
for l < r {
mid := (l + r + 1) >> 1
if q[mid] <= x {
l = mid
} else {
r = mid - 1
}
}
fmt.Printf("%d\n", l)
}
return
}