https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/css
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.ide
Your algorithm's runtime complexity must be in the order of O(log n).spa
If the target is not found in the array, return [-1, -1]
.3d
Example 1:code
Input: nums = [, target = 8 Output: [3,4]5,7,7,8,8,10]
Example 2:blog
Input: nums = [, target = 6 Output: [-1,-1]5,7,7,8,8,10]
1 class Solution: 2 def searchRange(self, nums: List[int], target: int) -> List[int]: 3 if nums is None: 4 return [-1, -1] 5 6 def helper(nums, target, search_left_index): 7 left, right = 0, len(nums) 8 9 while left < right: 10 middle = (left + right) // 2 11 12 # check if searching the leftmost index or not 13 if nums[middle] > target or (search_left_index and nums[middle] == target): 14 right = middle 15 else: 16 left = middle + 1 17 18 return left 19 20 left_index = helper(nums, target, True) 21 22 if left_index == len(nums) or nums[left_index] != target: 23 return [-1, -1] 24 25 return [ left_index, helper( nums, target, False ) - 1 ]