34. Find First and Last Position of Element in Sorted Array
Problem 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:1
2Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:1
2Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Solution:
First, let’s find the left boundary of the range. We initialize the range to [left=0, right=n-1]
. In each step, calculate the middle element mid = left+(right-left)/2
. Now according to the relative value of A[mid] to target, there are three possibilities:
- If
A[mid] < target
, the target range must begins on the right of mid (henceleft = mid+1
for the next iteration) - If
A[mid] > target
, it means the range must begins on the left of mid (right = mid-1
) - If
A[mid] = target
, then the range must begins on the left of or at mid (right= mid
)
With above mid finding way, the mid will always biased toward left. So we can find the left boundary
of target.
That is to say, if we make mid
biased toward right, we can find right boundary
of target.
We can use mid = left+(right-left)/2 +1
.
- If A[mid] > target, then the range must begins on the left of mid (
right = mid-1
) - If A[mid] < target, then the range must begins on the right of mid (hence
left = mid+1
for the next iteration) - If A[mid] = target, then the range must begins on the right of or at mid (
left= mid
)
1 | class Solution: |
1 | class Solution { |
time complexity: $O(logn)$
space complexity: $O(1)$
reference:
https://goo.gl/hL7qEx