Search for a Range
Question
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]
.
Tags
- Array
- Binary Search
Thought
We still use binary search here:
- Search the start index of the range by searching the index of
target - 0.5
. - Search the end index of the range by searching the index of
target + 0.5
. - Check validation of the start index and the end index
Code
class Solution(object):
def binarySearch(self, nums, target):
start, end = 0, len(nums) - 1
while start < end:
mid = (start + end) / 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
start = mid + 1
else:
end = mid - 1
return start
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# binary search
if len(nums) == 0:
return [-1, -1]
startIndex = self.binarySearch(nums, target - 0.5)
endIndex = self.binarySearch(nums, target + 0.5)
if nums[startIndex] < target:
startIndex += 1
if nums[endIndex] > target:
endIndex -= 1
if startIndex > endIndex:
return [-1, -1]
else:
return [startIndex, endIndex]