题目
题解
思路:二分
二分模板1:
while l < r:
mid = (l + r)//2
if 条件:
r = mid
else:
l = mid + 1
return r
二分模板2:
while l < r:
mid = (l + r + 1)//2
if 条件:
l = mid
else:
r = mid - 1
return r
根据使用策略使用两种模板,例如本题求左边第一个target,那就是把右边往左缩小,就是r = mid的版本;求右边最后一个target,那就是把左边往右缩小,就是l=mid的版本;
class Solution(object):
def searchRange(self,nums, target):
if len(nums) == 0:
return [-1, -1]
l, r = 0, len(nums)-1
while l < r:
mid = (l + r)//2
if nums[mid] >= target:
r = mid
else:
l = mid + 1
if nums[r] != target:
return [-1, -1]
L = r
l, r = 0, len(nums)-1
while l < r:
mid = (l + r + 1)//2
if nums[mid] <= target:
l = mid
else:
r = mid - 1
return [L, r]