You are given an array of integers nums sorted in non-decreasing order, and an integer target. Your task is to find the starting and ending position of a given target value in the array.
Return an array of length 2, where the first element is the starting position and the second element is the ending position of target. If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
[-1, -1].[-1, -1].To achieve the required O(log n) time complexity, we can use a binary search approach. Here’s the plan:
target:
target.left to 0 and right to the length of the array minus one.target, eliminate the right half; otherwise, eliminate the left half.target:
target.left to 0 and right to the length of the array minus one.target, eliminate the left half; otherwise, eliminate the right half.-1.def searchRange(nums, target):
def findFirst(nums, target):
left, right = 0, len(nums) - 1
first_pos = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
first_pos = mid
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return first_pos
def findLast(nums, target):
left, right = 0, len(nums) - 1
last_pos = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
last_pos = mid
left = mid + 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return last_pos
first_pos = findFirst(nums, target)
last_pos = findLast(nums, target)
return [first_pos, last_pos]
# Example Usage
nums = [5,7,7,8,8,10]
target = 8
print(searchRange(nums, target)) # Output: [3, 4]
O(log n) because it uses a binary search.O(log n) for the same reason.O(log n).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?