Created
October 9, 2024 22:20
-
-
Save hongtaoh/6310e175e148243ce751f9ae58ab8ea8 to your computer and use it in GitHub Desktop.
Solution to Leetcode 34 Find First and Last Position of Element in Sorted Array
This file contains hidden or 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]: | |
left = self.binSearch(nums, target, True) | |
right = self.binSearch(nums, target, False) | |
return [left, right] | |
# modified binary search algorithm | |
def binSearch(self, nums, target, leftBiased): | |
l = 0 | |
r = len(nums) - 1 | |
i = -1 | |
while l<=r: | |
m = (l+r)//2 | |
if nums[m] < target: | |
l = m+1 | |
elif nums[m] > target: | |
r = m-1 | |
else: | |
i = m | |
if leftBiased: | |
r = m-1 | |
else: | |
l = m+1 | |
return i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment