Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
题意:在一个有序数组中 查找某个target的范围,返回起始索引。
如果查找不到,返回[-1,-1]。要求算法复杂度logn。
直接二分查找到target的索引,然后往前后判断是否等于target。
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l,r=0,len(nums)-1
t=-1
a=[]
if r==-1:return [-1,-1]
while(l<=r):
m=(l+r)/2
if(nums[m]==target):
t=m
break
if(nums[m]>target):r=m-1
else:l=m+1
if t==-1:return [-1,-1]
while(m>=0):
if(nums[m]!=target):
break
m=m-1
a.append(m+1)
while(t<=(len(nums)-1)):
if(nums[t]!=target):
break
t=t+1
a.append(t-1)
return a