AcWing 789. 数的范围
原题链接
简单
作者:
upupgo
,
2021-07-17 19:31:58
,
所有人可见
,
阅读 302
Golang优雅写法
package main
import "fmt"
func BinarySearch(arr []int, target int) int {
l := 0
r := len(arr) - 1
for l < r {
mid := (l + r) >> 1
if arr[mid] >= target {
r = mid
} else {
l = mid + 1
}
}
return l
}
func BinarySearch1(arr []int, target int) int {
l := 0
r := len(arr) - 1
for l < r {
mid := (l + r + 1) >> 1
if arr[mid] <= target {
l = mid
} else {
r = mid - 1
}
}
return l
}
func DoBlackInput(n int) []int {
arr := make([]int, n)
for i := 0; i < n; i++ {
fmt.Scan(&arr[i])
}
return arr
}
func main() {
var n int
var q int
fmt.Scan(&n, &q)
arr := DoBlackInput(n)
for i:=0; i<q;i++ {
var target int
fmt.Scan(&target)
x := BinarySearch(arr, target)
if arr[x] != target {
fmt.Println("-1 -1")
continue
}
y := BinarySearch1(arr, target)
fmt.Printf("%d %d\n", x, y)
}
}