Created
March 8, 2019 21:40
-
-
Save mylons/dceb8df76373faee66c30eabf52fb6f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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