在排序数组中查找元素的第一个和最后一个位置
Binary Search; Easy;
Last updated
Binary Search; Easy;
Last updated
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
#
#input: sorted array output: indices/positions of start and end of target
# idea: binary search
# 1. start from left and right of array to search target
# 2. find the left boundary/the first occurance of target
# 3. find the right boundary/the last occurance of target
# 4. return start and end
if not nums:
return [-1, -1]
# find first occurance
left, right = 0, len(nums)-1
start =-1
end = -1
while left < right -1:
mid = (left + right)//2
if nums[mid] >= target:
right = mid
else:
left = mid
if nums[left] == target:
start = left
elif nums[right] == target:
start = right
left = start
right = len(nums)-1
while left < right -1:
mid = (left + right)//2
if nums[mid] > target:
right = mid
else:
left = mid
if nums[right] == target:
end = right
elif nums[left] == target:
end = left
return [start, end]