The title

Given an array of ascending integers, nums, and a target value. Find the start and end positions in the array for the given target value.

Return [-1, -1] if there is no target value in the array.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8Copy the code

Example 2:

Nums = [5,7,7,8,8,10], target = 6 output: [-1,-1]Copy the code

Example 3:

Nums = [], target = 0 Output: [-1,-1]Copy the code

Tip:

Length <= 105-109 <= nums[I] <= 109 Nums is a non-decreasing array -109 <= target <= 109Copy the code

Train of thought

I’m going to look for the first index l that is equal to the target, starting from the left,

I’m going to look for the first index r that is equal to the target, starting from the right,

Return subvalue, if not, return [-1,-1]

Write your own GO code

func searchRange(nums []int, target int) []int { l := 0 r := len(nums) - 1 if l == r && nums[l] == target { return []int{l, r} } for l < r { for nums[l] ! = target && l < r { l++ } for nums[r] ! = target && l < r { r-- } if nums[l] == target && nums[r] == target { return []int{l, r} } } return []int{-1, -1} }Copy the code

Official GO code

func searchRange(nums []int, target int) []int { leftmost := sort.SearchInts(nums, target) if leftmost == len(nums) || nums[leftmost] ! = target { return []int{-1, -1} } rightmost := sort.SearchInts(nums, target + 1) - 1 return []int{leftmost, rightmost} }Copy the code