NOTE
Binary Search
Given an n-element sorted (ascending) integer array nums and a target value target, write a function to search for target in nums. If the target exists, return its index; otherwise return -1.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given an n-element sorted (ascending) integer array nums and a target value target, write a function to search for target in nums. If the target exists, return its index; otherwise return -1.
2. Approach
3. Implementation
func search(nums []int, target int) int {
left := 0
right := len(nums)-1
for left <= right {
mid := left+(right-left)/2
if nums[mid] == target {
return mid
}else if nums[mid] < target {
left = mid+1
}else {
right = mid -1
}
}
return -1
}
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub