34. Find First and Last Position of Element in Sorted Array
Description
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Exceptions
There will be a chance that the target cannot be found in the array.
Python Code
The array is sorted and we need a O(logn) solution. So we can use the binary search template to find the first target and then find the last target.The only difference is:
find first: if nums[mid] == target: end = mid
and check if nums[start] == target in the end.
find last: if nums[mid] == target: start = mid
and check if nums[end] == target in the end.
def searchRange(self, nums: List[int], target: int) -> List[int]:
if not nums:
return [-1, -1]
start, end = 0, len(nums) - 1
res = [-1, -1]
#find first
'''
remember start < end - 1 to avoid infinite loop
'''
while start < end - 1:
mid = (start + end) // 2
'''
mid need to be included as well
'''
if nums[mid] >= target:
end = mid
else:
start = mid
'''
check start first since we are finding the first target position
'''
if nums[start] == target:
res[0] = start
elif nums[end] == target:
res[0] = end
# find last
start, end = 0, len(nums) - 1
while start < end - 1:
mid = (start + end) // 2
if nums[mid] <= target:
start = mid
else:
end = mid
if nums[end] == target:
res[1] = end
elif nums[start] == target:
res[1] = start
return res