leetcode [34] 在排序数组中查找元素的第一个和最后一个位置
Contact me:
Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums) == 0:
return [-1, -1]
low, high = 0, len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] == target:
low = high = mid
while low - 1 >= 0 and nums[low - 1] == target:
low -= 1
while high + 1 < len(nums) and nums[high + 1] == target:
high += 1
return [low, high]
if nums[mid] < target:
low = mid + 1
else:
high = mid
return [-1, -1]
优化:
由于找到相等的时候,退化为线性查找,优化为对数查找, 注意细节:
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums) == 0:
return [-1, -1]
low, high = 0, len(nums)
while low < high:
mid = (low + high) // 2
if nums[mid] == target:
result = []
left, right = low, mid
# 查找左边界
while left < right:
newmid = (left + right) // 2
if nums[newmid] < target:
left = newmid + 1
else:
right = newmid
result.append(left)
left, right = low, high
# 查找右边界
while left < right:
newmid = (left + right) // 2
if nums[newmid] > target:
right = newmid
else:
left = newmid + 1
result.append(right - 1)
return result
if nums[mid] < target:
low = mid + 1
else:
high = mid