Skip to content

Instantly share code, notes, and snippets.

@mylons
Created March 8, 2019 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mylons/dceb8df76373faee66c30eabf52fb6f0 to your computer and use it in GitHub Desktop.
Save mylons/dceb8df76373faee66c30eabf52fb6f0 to your computer and use it in GitHub Desktop.
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums) == 0:
return [-1, -1]
if len(nums) == 1:
if target == nums[0]:
return [0, 0]
def binary_search(left, right):
mid = math.floor((left + right) / 2)
if mid >= len(nums) or left > right:
return -1
num = nums[mid]
if num == target:
return mid
elif target < num:
# go left
return binary_search(left, mid - 1)
else:
# go right
return binary_search(mid + 1, right)
a_location = binary_search(0, len(nums))
if a_location >= 0:
left_bound = a_location
while left_bound >= 0 and nums[left_bound] == target: left_bound -= 1
right_bound = a_location
while right_bound < len(nums) and nums[right_bound] == target: right_bound += 1
return [left_bound + 1, right_bound - 1]
else:
return [-1, -1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment