# 34. Find First and Last Position of Element in Sorted Array

## Description

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

``````Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
``````

Example 2:

``````Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
``````

Tags: Math, String

## 题解

### 思路1

``````unc searchRange(nums []int, target int) []int {
targetRange := []int{-1, -1}

for i := 0; i < len(nums); i++ {
if nums[i] == target {
targetRange[0] = i
break
}
}
if targetRange[0] == -1 {
return targetRange
}

for j := len(nums) - 1; j >= 0; j-- {
if nums[j] == target {
targetRange[1] = j
break
}
}
return targetRange
}
``````

### 思路2

``````if leftIndex == len(nums) || nums[leftIndex] != target {
return targetRange
}

targetRange[0] = leftIndex
targetRange[1] = extremeInsertionIndex(nums, target, false) - 1

return targetRange
``````

} func extremeInsertionIndex(nums []int, target int, left bool) int { lo := 0 hi := len(nums) for lo < hi { mid := (lo + hi) / 2 if nums[mid] > target || left && target == nums[mid] { hi = mid } else { lo = mid + 1 } } return lo }

```