def canShip(opacity):
# 指定船的容量是否可以在D天运完
lo = 0
hi = total # total 其实就是 sum(weights)
while lo <= hi:
mid = (lo + hi) // 2
if canShip(mid):
hi = mid - 1
else:
lo = mid + 1
return lo
这其实就是我二分专题里的最左二分,大家直接套这个模板就行了。
关键点解析
能力检测二分
代码
语言支持:JS,Python
Python Code:
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
def possible(mid):
days = 1
cur = 0
for w in weights:
if w > mid:
return False
if cur + w > mid:
cur = 0
days += 1
cur += w
return days <= D
l, r = 1, sum(weights)
while l <= r:
mid = (l + r) // 2
if possible(mid):
r = mid - 1
else:
l = mid + 1
return l
JS Code:
/**
* @param {number[]} weights
* @param {number} D
* @return {number}
*/
var shipWithinDays = function (weights, D) {
let high = weights.reduce((acc, cur) => acc + cur);
let low = 0;
while (low < high) {
let mid = Math.floor((high + low) / 2);
if (canShip(mid)) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
function canShip(opacity) {
let remain = opacity;
let count = 1;
for (let weight of weights) {
if (weight > opacity) {
return false;
}
remain -= weight;
if (remain < 0) {
count++;
remain = opacity - weight;
}
if (count > D) {
return false;
}
}
return count <= D;
}
};
复杂度分析
令 n 为 weights 长度。
时间复杂度:$O(nlogn)$
空间复杂度:$O(1)$
以上就是本文的全部内容了。大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 40K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。