Created
September 13, 2015 19:05
-
-
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/
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(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