Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode 34. Find First and Last Position of Element in Sorted Array
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
if n == 0:
return [-1, -1]
lo = 0
hi = n - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] >= target:
hi = mid
else:
lo = mid + 1
if nums[lo] > target:
return [-1, -1]
res = [lo, -1]
lo = 0
hi = n - 1
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if nums[mid] <= target:
lo = mid
else:
hi = mid - 1
if nums[lo] < target:
return [-1, -1]
res[1] = lo
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment