參考 LeetCode Binary Search Summary 二分搜索法小结 的 python 版
今天偷懶一下,拿以前的小筆記來自我抄襲。
def binary_search(nums, target):
l, r = 0, len(nums)
while l < r:
mid = l + (r - l) // 2
if nums[mid] == target :
return mid
elif nums[mid] < target:
l = mid + 1
else:
r = mid
return -1
可變動的 4 個地方:
len(nums)
或 len(nums) - 1
l < r
或 l <= r
r = mid
或 r = mid - 1
l
或 r
或 r-1
r = len(nums)
l < r
r = mid
r = len(nums) - 1
l <= r
r = mid - 1
nums[mid] == target
判斷第一個不小於目標的數
# [1, 1, 2, 3, 6] t = 4
def bs_lowerbound(nums, target):
l, r = 0, len(nums)
while l < r:
mid = l + (r - l) // 2
if nums[mid] < target:
l = mid + 1
else:
r = mid
return r
往前退,就是 最後一個小於目標的數
return r - 1 即可
除了 == 部分,其他都一樣。
# [1, 1, 2, 3, 6] t = 4
def bs_upperbound(nums, target):
l, r = 0, len(nums)
while l < r:
mid = l + (r - l) // 2
if nums[mid] <= target: # == 時也要移動左邊界
l = mid + 1
else:
r = mid
return r
return r - 1 即可
難QQ 要經驗
Minimize Max Distance to Gas Station
Swim in Rising Water
Split Array Largest Sum
Guess Number Higher or Lower
Find K Closest Elements
Find K-th Smallest Pair Distance
Kth Smallest Number in Multiplication Table
Maximum Average Subarray II
Koko Eating Bananas
Nth Magical Number
Find Peak Element
H-Index II