Skip to content

Instantly share code, notes, and snippets.

@junjiah
Created September 13, 2015 19:05
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 junjiah/be399d7fd70e4130f110 to your computer and use it in GitHub Desktop.
Save junjiah/be399d7fd70e4130f110 to your computer and use it in GitHub Desktop.
solved 'Search for a Range' on LeetCode https://leetcode.com/problems/search-for-a-range/
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = self.lowerBound(nums, target)
if left == len(nums) or nums[left] != target:
return (-1, -1)
else:
return (left, self.lowerBound(nums, target + 1) - 1)
def lowerBound(self, nums, target):
"""Find the index of first element >= target."""
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) / 2
if nums[mid] < target:
lo = mid + 1
elif nums[mid] >= target:
hi = mid
return lo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment