Problem
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:
1 |
|
Example 2:
1 |
|
Explanation
-
The array is sorted and and we need the runtime be $O(\log n)$, so we use binary search.
-
To find the first and last index of the target elements, when we do binary search, we do not need to consider the case
if target == nums[mid], return mid
. We can keep divide and conquer the array. -
To find the first index of the target, when
target == nums[mid]
ortarget < nums[mid]
, the right is moving toward mid and we check the left first. To find the last index of the target, whentarget == nums[mid]
ortarget > nums[mid]
, the left is moving toward mid and we check the right first.
Solution 1
1 |
|
Solution 2
1 |
|
Solution 3
1 |
|