package main
import "fmt"
//二分法最关键的地方在于:确定target元素位于哪个区间? (left, mid) or (mid, right)
func solution(nums []int, target int) int {
if nums == nil {
return -1
}
left, right := 0, len(nums)-1
for left <= right { /*注意循环条件为: left <= right*/
mid := left + (right-left)>>1 //left+right可能会出现溢出导致除以2时获取的值有误
if nums[mid] == target { /*找到了元素*/
return mid
} else if nums[mid] < target { //向右移动, 注意: left = mid + 1
left = mid + 1
} else if nums[mid] > target { //向左移动, 注意: right = mid - 1
right = mid - 1
}
}
return -1
}
func main() {
fmt.Println(solution([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 3))
fmt.Println(solution([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 5))
fmt.Println(solution([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 30))
fmt.Println(solution([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 0))
fmt.Println(solution([]int{1, 2, 2, 2, 2}, 2))
fmt.Println(solution([]int{1}, 1))
}