所有的binary search 问题都可以变换成找 first xxx 或者last xxx的问题。
注意是return first, last 还是 any.
first: 1 end 前移 (mid = target, end=mid)
2 最后先check start =target
last : 1 start 后移
2 最后先check end =target
For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity. If the target number does not exist in the array, return -1.
<span style="color:#666e70;">def binarySearch(self, nums, target):
if len(nums) == 0:
return -1
start, end = 0, len(nums)-1
while </span><span style="color:#ff0000;">start + 1 < end:</span><span style="color:#666e70;">
mid = (start + end)/2
if nums[mid] < target:
start = mid
else:
</span><span style="color:#ff0000;">end = mid</span><span style="color:#666e70;"> # end move forward if nums[mid] == target 否则会略过mid之前的target
if nums[start] == target:
return start
if nums[end] == target:
return end
return -1</span>
For a given sorted array (ascending order) and a target number, find the last index of this number in O(log n) time complexity. If the target number does not exist in the array, return -1.
def binarySearchLast(nums, target):
if len(nums) == 0:
return -1
start, end = 0, len(nums) - 1
while start + 1 < end:
mid = (start + end)/2
if nums [mid] > target:
end = mid
else:
start = mid
if nums[end] == target:
return end
if nums[start] == target:
return start
return -1
Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not found in the array, return [-1, -1]
.
其实就是找到first position 和 last position 就可以了
def searchRange(self, A, target):
if len(A) == 0:
return [-1, -1]
start, end = 0, len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if A[mid] < target:
start = mid
else:
end = mid
if A[start] == target:
leftBound = start
elif A[end] == target:
leftBound = end
else:
return [-1, -1]
start, end = leftBound, len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if A[mid] <= target:
start = mid
else:
end = mid
if A[end] == target:
rightBound = end
else:
rightBound = start
return [leftBound, rightBound]
3 Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:Integers in each row are sorted from left to right.The first integer of each row is greater than the last integer of the previous row.
可以用两次BS, 一次确定row, 一次确定 column.
或者把它连起来看成一个ascending array,然后直接bs,注意比较 A[mid] 和 target时如何把mid 转化为matrix 里的下标
def searchMatrix(self, matrix, target):
# Solution 2 binary search once, treated as an ascending array
if len(matrix) == 0:
return False
m = len(matrix)
n = len(matrix[0])
start, end = 0, m*n - 1
while start + 1 < end:
mid = (start + end) / 2
x = mid / n
y = mid % n
if matrix[x][y] < target:
start = mid
else:
end = mid
x, y = start / n, start % n
if matrix[x][y] == target:
return True
x, y = end / n, end % n
if matrix[x][y] == target:
return True
return False