Get idea from here
Question
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].
Analysis
Since the complexity is required to be O(log n), it is highly possible that binary search is needed. In the standard binary search, we will stop while finding the right element. In this problem, we have to keep searching its left most one and right most one.
Another thing should be noticed is that maybe this element is on the boundary or its left and right part has no the same element. We have to consider it using if-else.
We add a new parameter LorR, meaning it will keep searching left(right) most target value when finding the target in the mid.
Solution
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def searchRange(self, nums, target):
if len(nums)==0 or target==None:
return [-1, -1]
result = [-1,-1]
result[0] = self.search(nums, target, 0, len(nums)-1, 0)
result[1] = self.search(nums, target, 0, len(nums)-1, 1)
return result
# LorR: 0(left), 1(right)
def search(self, nums, target, left, right, LorR):
if left>right:
return -1
mid = (left + right)/2
if target<nums[mid]:
return self.search(nums,target,left, mid-1, LorR)
elif nums[mid]<target:
return self.search(nums,target,mid+1,right, LorR)
else:
if LorR==0:
if mid==0 or nums[mid-1]<nums[mid]:
return mid
else:
return self.search(nums,target,left,mid-1,0)
elif LorR==1:
if mid==len(nums)-1 or nums[mid]<nums[mid+1]:
return mid
else:
return self.search(nums,target,mid+1,right,1)