Created
December 7, 2018 05:11
-
-
Save jovianlin/b7e37ec15ee86bd797b723d1759e5f56 to your computer and use it in GitHub Desktop.
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): | |
""" | |
:type nums: List[int] | |
:type target: int | |
:rtype: List[int] | |
""" | |
def searchOccurrence(nums, target, isFirst): | |
N = len(nums) | |
if N == 1: | |
return 0 if target == nums[0] else -1 | |
start, end = 0, N-1 | |
result = -1 | |
while start < end: | |
mid = start+(end-start)//2 | |
# If target is found, search LEFT, BUT also INCLUDE the mid's value. | |
if nums[mid] == target: | |
result = mid | |
if isFirst: | |
end = mid-1 | |
else: | |
start = mid+1 | |
# If target's value is smaller than mid's value, search LEFT | |
elif target < nums[mid]: | |
end = mid-1 | |
# Else, search RIGHT | |
else: | |
start = mid+1 | |
# End of while loop. | |
return start if (start==end and nums[start]==target) else result | |
# End of helper | |
first = searchOccurrence(nums, target, isFirst=True) | |
last = searchOccurrence(nums, target, isFirst=False) | |
return [first, last] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment