Created
May 24, 2018 15:40
-
-
Save Alescontrela/b8fd35acbf9e4af1f18c3bbeaba0fd3b to your computer and use it in GitHub Desktop.
Search for a range
This file contains 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, target): | |
if len(nums) == 0: | |
return [-1,-1] | |
if (len(nums) == 1): | |
if nums[0] != target: | |
return [-1, -1] | |
return [0, 0] | |
""" | |
:type nums: List[int] | |
:type target: int | |
:rtype: List[int] | |
""" | |
ind = self.bsearch(nums, 0, len(nums), target) | |
print("ind of {} for value {} is {}".format(nums, target, ind)) | |
right_ind1 = ind | |
curr_left = ind | |
left_ind1 = 0 | |
while left_ind1 != -1: | |
left_ind1 = self.bsearch(nums, left_ind1, right_ind1, target) | |
if left_ind1 != -1: | |
curr_left = left_ind1 | |
print("Start for val {} is {}".format(target, curr_left)) | |
right_ind2 = len(nums) | |
curr_right = ind | |
left_ind2 = ind | |
while right_ind2 != -1: | |
right_ind2 = self.bsearch(nums, left_ind2, right_ind2, target) | |
if right_ind2 != -1: | |
curr_right = right_ind2 | |
print("End for val {} is {}".format(target, curr_right)) | |
return [curr_left, curr_right] | |
# checking left | |
# start = ind | |
# for i in reversed(range(ind, 0)): | |
# if nums[i] == target: | |
# start = i | |
# else: | |
# break | |
# print("Start for val {} is {}".format(target, start)) | |
# checking right | |
# end = ind | |
# for i in range(ind, len(nums)-1): | |
# if nums[i] == target: | |
# end = i | |
# else: | |
# break | |
def bsearch(self, li, l, r, val): | |
if r-l <= 1 and li[0]!= val: | |
return -1 | |
mid = (r+l)//2 | |
if li[mid] == val: | |
return mid | |
if val < li[mid]: | |
return self.bsearch(li, l, mid, val) | |
if val > li[mid]: | |
return self.bsearch(li, mid, r, val) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment