问题:给定一个有序数组和一个目标值,输出目标值在数组中的起始位置和终止位置,如果目标值不在数组中,则输出[-1,-1]
示例:
输入:nums = [1,2,3,5,5,7] target = 5
输出:[3,4]
输入:nums = [1,5,8,9] target = 7
输出:[-1,-1]
解决思路:二分查找直到找到第一个目标值,再对目标值左右进行二分查找
Python代码:
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ l = 0 r = len(nums)-1 while l <= r : mid = (l+r)//2 if nums[mid] > target: r = mid - 1 elif nums[mid] < target: l = mid + 1 else: first,last = mid,mid while l <= first: fm = (first+l) // 2 if nums[fm] < target: l = fm + 1 else: first = fm -1 while r >= last: rm = (last+r) // 2 if nums[rm] > target: r = rm - 1 else: last = rm + 1 return [first+1,last-1] return [-1,-1]
原文地址:https://www.cnblogs.com/wenqinchao/p/10728764.html
时间: 2024-11-05 22:52:21