题目描述:
给定一个按照升序排列的整数数组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]
代码看着有点长,其实思路很简单,先利用二分查到确定元素位置mid,再从mid前后探索start和end
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
mid = -1
end = -1
start = -1
left = 0
right = len(nums) - 1
res = [-1, -1]
if len(nums) == 0:
return res
if len(nums) == 1 and nums[0] == target:
res = [0, 0]
return res
while left <= right:
l = (left + right) // 2
if target > nums[l]:
left = l + 1
elif target < nums[l]:
right = l - 1
else:
mid = l
break
if mid == -1:
return res
else:
i = j = mid
while i <= len(nums)-1:
if nums[i] != target:
end = i - 1
break
end = i
i += 1
while j >= 0:
if nums[j] != target:
start = j + 1
break
start = j
j -= 1
res = [start, end]
return res