Created
October 8, 2020 06:53
-
-
Save vancexu/b480c999aa1a8da495433fb6e5e380fd to your computer and use it in GitHub Desktop.
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