关于二分查找
Posted Aiden_Zhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于二分查找相关的知识,希望对你有一定的参考价值。
二分查找
二分查找及其应用整理(假设数组有序)。
1. 查找与target相等的数字
def binarySearch(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target: return mid
elif arr[mid] > target: right = mid - 1
else: left = mid + 1
return -1
2. 查找最后一个小于target的数字
def binarySearch(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] >= target: right = mid - 1
else: left = mid + 1
return right if right >= 0 else -1
3. 查找最后一个小于等于target的数字
def binarySearch(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] > target: right = mid - 1
else: left = mid + 1
return right if right >= 0 else -1
4. 查找第一个大于target的数字
def binarySearch(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] <= target: left = mid + 1
else: right = mid - 1
return left if left < len(arr) else -1
5. 查找第一个大于等于target的数字
def binarySearch(arr, target):
left, right = 0, len(arr)-1
while left <= right:
mid = (left + right) // 2
if arr[mid] < target: left = mid + 1
else: right = mid - 1
return left if left < len(arr) else -1
6. 查找最接近target的数字
def binarySearch(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] <= target: left = mid + 1
else: right = mid - 1
if left >= len(arr): return len(arr) - 1
return left if left == 0 or arr[left]-target <= target-arr[left-1] else left - 1
以上是关于关于二分查找的主要内容,如果未能解决你的问题,请参考以下文章