Leetcode 34. Find First and Last Position of Element in Sorted Array
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: List[int], target: int) -> List[int]: | |
n = len(nums) | |
if n == 0: | |
return [-1, -1] | |
lo = 0 | |
hi = n - 1 | |
while lo < hi: | |
mid = lo + (hi - lo) // 2 | |
if nums[mid] >= target: | |
hi = mid | |
else: | |
lo = mid + 1 | |
if nums[lo] > target: | |
return [-1, -1] | |
res = [lo, -1] | |
lo = 0 | |
hi = n - 1 | |
while lo < hi: | |
mid = lo + (hi - lo + 1) // 2 | |
if nums[mid] <= target: | |
lo = mid | |
else: | |
hi = mid - 1 | |
if nums[lo] < target: | |
return [-1, -1] | |
res[1] = lo | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment