BinarySearch
#NeetCode150 #Easy
LeetCode.icon問題
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.
解法
時間計算量 O(log N)
空間計算量 O(1)
code:main.go
func search(nums []int, target int) int {
l, r := 0, len(nums)-1
for {
if l > r { break }
mid := l + (r-l)/2
if numsmid == target { return mid }
if numsmid > target {
r = mid-1
} else {
l = mid+1
}
}
return -1
}