0034.在排序数组中查找元素的第一个和最后一个位置
方法一:二分搜索
时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。
func searchRange(nums []int, target int) []int {
return []int{leftBound(nums, target), rightBound(nums, target)}
}
func leftBound(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
mid := left + (right-left)>>1
if nums[mid] >= target {
right = mid - 1
} else {
left = mid + 1
}
}
if left < len(nums) && nums[left] == target {
return left
}
return -1
}
func rightBound(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
mid := left + (right-left)>>1
if nums[mid] <= target {
left = mid + 1
} else {
right = mid - 1
}
}
if right >= 0 && nums[right] == target {
return right
}
return -1
}