34. Find First and Last Position of Element in Sorted Array
Medium
10708294Add to ListShare
Given an array of integers nums
sorted in non-decreasing 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] <= 109
nums
is a non-decreasing array.-109 <= target <= 109
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
"""
assert Solution().searchRange([0, 0, 0, 1, 2, 3], 0) == [0, 2]
assert Solution().searchRange([2, 2], 3) == [-1, -1]
assert Solution().searchRange([2, 2, 2], 2) == [0, 2]
assert Solution().searchRange([1, 2, 2, 2, 4], 2) == [1, 3]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert Solution().searchRange([], 8) == [-1, -1]
# 87ms
if target not in nums: return [-1,-1]
l = bisect_left(nums,target)
r = bisect_right(nums,target)
return [l,r-1]
解题思路:二分查找最左和最右
时间复杂度:O(logn) 99ms
"""
if nums is None or len(nums) <= 0:
return [-1, -1]
# 二分查找最左
def findL(l: int, r: int) -> int:
if l >= r:
if l < len(nums) and nums[l] == target:
return l
return -1
mid = int((l + r) / 2)
if nums[mid] >= target:
# 保留mid,接着往左寻
return findL(l, mid)
return findL(mid + 1, r)
# 二分查找最右
def findR(l: int, r: int) -> int:
if l >= r:
if l < len(nums) and nums[l] == target:
return l
return -1
mid = int((l + r) / 2)
if nums[mid] == target:
if mid + 1 < len(nums) and nums[mid + 1] == target:
# 右边还有
return findR(mid + 1, r)
return mid
elif nums[mid] < target:
return findR(mid + 1, r)
return findR(l, mid - 1)
# 拆开会比直接返回[findL(0, len(nums)),findR(0, len(nums))]快
l = findL(0, len(nums))
r = findR(0, len(nums))
return [l, r]