您的位置:首页 > 编程语言 > Python开发

Leetcode_34. Search for a Range

2018-03-27 10:39 344 查看
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]
.
# 这题陷阱贼多。
# 解题思路:
两个反方向的binary search确定range. 但是要格外小心,只有一个element的list和target not in list的情况。比如【1】,1
应该返回[0,0].
以下代码:class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return -1,-1

left,right=-1,-1

start,end=0,len(nums)-1

while(start<end):
mid=start+(end-start)//2
if nums[mid]<target:
start=mid+1
else:
end=mid

left=start

start,end=left,len(nums)-1

while(start<end):
mid=(end+start)//2+1
if nums[mid]>target:
end=mid-1
else:
start=mid

if nums[start]!=target:
return -1,-1

right=end

return left,right
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息