原题地址:https://oj.leetcode.com/problems/search-for-a-range/
要求从一个有序的整数序列中,找到对应的target的范围,如果找不到返回[-1,-1],要求时间复杂度为O(log n),例如[5, 7, 7, 8, 8, 10]中8的范围为[3,4]
要求复杂度为O(logn)一般会联想到二分法,一般我们实现的二分法是利用迭代,并且只要查到就返回索引。但是这题要求的是返回一个范围,也就是说即使找到了某个值,还要继续寻找,因为可能前面跟后面都有这个值。所以在二分法的基础上,再分情况讨论:(设左边为left,右边为right,mid=(left+right)/2)
1.mid>target时,只需要在left,mid-1范围查找
2.mid<target时,只需要在mid+1,right范围查找
3.mid==target时,需要在两范围继续查找,范围一:left,mid-1,范围二:mid+1,right
按照这个思路,我们需要利用递归的方法来实现二分法。代码如下:
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, A, target):
if len(A)==0:
return [-1,-1]
left,right = 0,len(A)-1
return self.searchIndex(A,left,right,target)
def searchIndex(self,A,left,right,target):
if left > right:
return [-1,-1]
ranges = []
mid = (left + right)/2
if A[mid] < target:
ranges = self.searchIndex(A,mid + 1,right,target)
elif A[mid]>target:
ranges = self.searchIndex(A,left,mid-1,target)
else:
ranges = [mid,mid]
lranges = self.searchIndex(A,left,mid-1,target)
rranges = self.searchIndex(A,mid+1,right,target)
if lranges[0]!=-1 and lranges[0]<mid:
ranges[0] = lranges[0]
if rranges[1]!=-1 and rranges[0]>mid:
ranges[1] = rranges[1]
return ranges
print Solution().searchRange([5, 7, 7, 8, 8, 10], 8)