Skip to content

Instantly share code, notes, and snippets.

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 jovianlin/b7e37ec15ee86bd797b723d1759e5f56 to your computer and use it in GitHub Desktop.
Save jovianlin/b7e37ec15ee86bd797b723d1759e5f56 to your computer and use it in GitHub Desktop.
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