https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
和 上题 Search in Rotated Sorted Array 一样,依旧是二分查 找相关的问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| func searchRange(nums []int, target int) []int { for start,end:=0,len(nums)-1;start<=end; { mid:=(start+end)/2 switch { case nums[mid]==target: l,r:=mid,mid for ;l>0 && nums[l-1]==target;l--{} for ;r<len(nums)-1 && nums[r+1]==target;r++{} return []int{l,r} case nums[mid]<target: start=mid+1 case nums[mid]>target: end=mid-1 } } return []int{-1,-1} }
|