您的位置:首页 > 其它

leetcode-34-search for a range

2016-09-14 14:41 405 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: