Merge pull request #192 from betNevS/master

添加 704. 二分查找 go 版本
This commit is contained in:
Carl Sun 2021-05-19 23:33:56 +08:00 committed by GitHub
commit e6db09215a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 42 additions and 1 deletions

View File

@ -214,6 +214,47 @@ class Solution:
Go
(版本一)左闭右闭区间
```go
func search(nums []int, target int) int {
high := len(nums)-1
low := 0
for low <= high {
mid := low + (high-low)/2
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid-1
} else {
low = mid+1
}
}
return -1
}
```
(版本二)左闭右开区间
```go
func search(nums []int, target int) int {
high := len(nums)
low := 0
for low < high {
mid := low + (high-low)/2
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid
} else {
low = mid+1
}
}
return -1
}
```