二分法
今天重新审视了二分法,结合同事的思考认为,
二分的本质是,在一段或多段单调序列里找分界点
使用左开右闭 [l, r)
的模板如下:
1 | def binary_search(l, r): |
m
如果满足查找条件,即 f(m)
返回 true
,则查找结束。如果 f(m)
返回 false
, 则根据 g(m)
的结果构造新的查找区间。如果新区间在左边,则新的左闭右开区间是 [l, m)
等价于 [l, m-1]
;如果新区间在右边,则新的左闭右开是 [m+1, r)
。
Return the lower_bound / upper_bound of a value x in a sorted array.
lower_bound(A, x): first index of i, such that A[i] >= x
1 | def lower_bound(A, x, l, r): |
if A[m] == x
, still need to update right bound to m as there are probable mutiple x at the left of m.
upper_bound(A, x): first index of i, such that A[i] > x
1 | def upper_bound(A, x, l, r): |
案例应用
案例 1:Capacity to Ship Packages Within D Days
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
1 | class Solution: |
案例 2:Coko Eating Bananas
https://leetcode.com/problems/koko-eating-bananas/
1 | class Solution: |