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.
If target
is not found in the array, return [-1, -1]
.
Follow up: Could you write an algorithm with O(log n)
runtime complexity?
Example 1:
Example 2:
Example 3:
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
is a non-decreasing array.-109 <= target <= 109
Tags
Array, Binary Search
Solution
Based on the binary search template, we need to re-design the case of nums[mid] == target
, because we do not want to return the found index immediately when it might not be either the starting or the ending position. In the case of equality of the both, if we need to find the starting position of target
, we assign mid
to r
. Otherwise we assign mid to l
. After the loop, If we are looking for the starting position, we check the nums[l]
first and then nums[r]
, otherwise the process is reversed. Return -1
when target
does not present in the array.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?