Junedayday Blog

六月天天的个人博客

0%

Go算法实战 - 12.【二分查找LeetCode-704】

Go-Leetcode

Leetcode-704 二分查找

原题链接 https://leetcode-cn.com/problems/binary-search/submissions/

1
2
3
func search(nums []int, target int) int {

}

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func search(nums []int, target int) int {
start, end := 0, len(nums)-1
// 注意,当nums长度为1时,start=end=0
// 所以这个判断逻辑要注意
for end >= start {
mid := (start + end) / 2
if nums[mid] == target {
return mid
} else if nums[mid] > target {
end = mid - 1
} else {
start = mid + 1
}
}
return -1
}

Github: https://github.com/Junedayday/code_reading

Blog: http://junes.tech/

Bilibili: https://space.bilibili.com/293775192

公众号: golangcoding

二维码