题目:
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]
.
思考:
这一题的思路比较简单,由于算法复杂度要求为O(logn),并且原数组是有序的,因此需要使用2分查找法去查找数字的位置,查到数字的位置后,则分别向前和向后去遍历数组,看相同数字的开始和结束位置即可。
代码:
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = -1
l = -1
low = 0
high = len(nums) - 1
while(low <= high):
mid = (low + high)/2
if nums[mid] < target:
low = mid + 1
elif nums[mid] > target:
high = mid - 1
else:
h = mid
l = mid
while h < len(nums) - 1 and nums[h+1] == target:
h += 1
while l > 0 and nums[l-1] == target:
l -= 1
break
return l,h
结果: