You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
34. Find First and Last Position of Element in Sorted Array (Medium)
find left bound using >=
find right bound using condition <=
classSolution:
defsearchRange(self, nums: List[int], target: int) ->List[int]:
ifnotnums:
return [-1, -1]
left, right=0, len(nums) -1count=0start, end=-1, -1# find the left bound using >=while(left<=right):
mid= (left+right) //2# shift to the right so will find the end.ifnums[mid] ==target:
end=midleft=mid+1elifnums[mid] <target:
left=mid+1else:
right=mid-1left, right=0, len(nums) -1# find the right bound using <=while(left<=right):
mid= (left+right) //2ifnums[mid] ==target:
# shift to the left so will find the start.start=midright=mid-1elifnums[mid] >target:
right=mid-1else:
left=mid+1return[start, end]