所有题目均采用python进行完成
二分搜索
二分搜索的简单模板
def binary_search(num, target):
# 判断是否为空
if len(num) == 0:
return -1
left = 0
right = len(num) - 1
while left + 1 < right:
mid = (left + right) // 2
if num[mid] == target:
right = mid
elif num[mid] < target:
left = mid
elif num[mid] > target:
right = mid
# 判断边界条件
if num[left] == target:
return left
if num[right] == target:
return right
return -1
旋转有序数列中寻找最小值
关键是找到拐点
def search(num):
if len(num) == 0:
return -1
left = 0
right = len(num) - 1
while left + 1 < right:
if num[left] < num[right]:
return num[left]
mid = left + (right - left) // 2
if num[left] <= num[mid]:
left = mid + 1
else:
right = mid
return num[left] if num[left] < num[right] else num[right]
旋转有序数组查找特定数
核心和上一个程序一样
def search_target(num, target):
if len(num) == 0:
return -1
left, right = 0, len(num) - 1
while left + 1 < right:
mid = left + (right - left) // 2
if num[mid] == target:
return mid
if num[left] < num[mid]:
if num[left] <= target and target <= num[mid]:
right = mid
else:
left = mid
else:
if num[mid] <= target and target <= num[right]:
left = mid
else:
right = mid
if num[left] == target:
return left
if num[right] == target:
return right
return -1
搜索插入位置
给定有序数组和目标值,如果找到目标数则返回索引值,没有找到就返回按顺序应该被插入的位置的索引
def search_insert_position(num, target):
if len(num) == 0:
return 0
left, right = 0, len(num)-1
while left + 1 < right:
mid = left + (right - left) // 2
if num[mid] == target:
return mid
if num[mid] > target:
right = mid
else:
left = mid
if num[left] >= target:
return left
if num[right] >= target:
return right
return right + 1
搜索区间
给定一个有序数组,找到给定目标的开始和结束位置
思路:找到第一次出现目标和最后一次出现目标的位置,写两个二分法
def search_area(num, target):
if len(num) == 0:
return (-1, -1)
# left bound
left, right = 0, len(num) - 1
while left + 1 < right:
mid = left + (right - left) // 2
if num[mid] == target:
right = mid
elif num[mid] > target:
right = mid
else:
left = mid
if num[left] == target:
lbound = left
elif num[right] == target:
lbound = right
else:
return (-1,-1)
# right bound
left, right = 0, len(num)-1
while left + 1 < right:
mid = left + (right - left) // 2
if num[mid] == target:
left = mid
elif num[mid] > target:
right = mid
else:
left = mid
if num[left] == target:
rbound = left
elif num[right] == target:
rbound = right
else:
return (-1, -1)
return (lbound, rbound)
带空字符串中,找到目标(有序数组)
时间复杂度 O(n)
首先确定左边 or 右边第一个字符的位置
def search_empty(num, target):
if len(num) == 0:
return -1
left, right, = 0, len(num)-1
while left + 1 < right:
while left + 1 < right and left == '':
if num[left] == '':
left += 1
if right < left:
return -1
mid = left + (right - left) // 2
if num[mid] == target:
return mid
if num[mid] < target:
left = mid + 1
else:
right = mid - 1
if num[left] == target:
return left
if num[right] == target:
return right
return -1