Tag
Binary Search\Array
Difficulty
Medium
Description
Given an array of integers sorted in ascending order, 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].
Code
用二分搜索
import sys
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if nums == []:
return [-1,-1]
start = 0
end = len(nums)
ret = [sys.maxint,-sys.maxint]
def find(start,end,ret):
#print start,end
while(start<end-1):
mid = (start + end)/2
#print start,end,mid
if nums[mid]<target:
start = mid
elif nums[mid]>target:
end = mid
else:
ret[0] = min(ret[0],mid)
ret[1] = max(ret[1],mid)
ret = find(start,mid,ret)
ret = find(mid,end,ret)
break
if nums[start] == target:
ret[0] = min(ret[0], start)
ret[1] = max(ret[1], start)
return ret
ret = find(start,end,ret)
if ret == [sys.maxint,-sys.maxint]:
return [-1,-1]
else:
return ret