Find First and Last Position of Element in Sorted Array Program (Leetcode):
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3:
Input: nums = [], target = 0 Output: [-1,-1]
Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109numsis a non-decreasing array.-109 <= target <= 109
#check move left or not
def binarySearch(self, nums, target, check):
left = 0
right = len(nums)
while left < right:
mid = (left + right) // 2
if (nums[mid] > target or (check and target == nums[mid])):
right = mid
else:
left = mid + 1
return left
def searchRange(self, nums: List[int], target: int):
left = self.binarySearch(nums, target, True)
if left == len(nums) or nums[left] != target:
return [-1, -1]
right = self.binarySearch(nums, target, False) - 1
return [left, right]
0 Comments
Please don't enter any spam link in comment box.
Emoji