34. Search for a Range
题目
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].
代码
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = len(nums)
if not l:
return [-1,-1]
r = list()
for i in range(l):
if nums[i] == target:
r.append(i)
if len(r)==1:
r.append(r[0])
return r
if len(r) > 2:
return [r[0],r[len(r)-1]]
if r:
return r
else:
return [-1,-1]
可惜的是,这个算法的时间复杂度是O(n),还有待改进