题目地址:
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/description/
给定一个长 n n n数组 a a a,代表每个货物的重量。有一个运输车,其有一个载重,它需要按照顺序将每个货物装载并运到另一个地方,每天运一次。再给定一个天数 d d d,问车的最小载重,使得运输的天数小于等于 d d d。
思路是二分答案。代码如下:
class Solution {
public:
int shipWithinDays(vector<int>& ws, int days) {
int l = 0, r = 0;
for (int x : ws) r += x, l = max(l, x);
auto f = [&](int cap) {
int days = 1, cur = 0;
for (int x : ws) {
if (cur + x > cap) {
cur = 0;
days++;
}
cur += x;
}
return days;
};
while (l < r) {
int mid = l + (r - l >> 1);
if (f(mid) <= days) r = mid;
else l = mid + 1;
}
return l;
}
};
时间复杂度 O ( n log ∑ i a i ) O(n\log \sum_i a_i) O(nlog∑iai),空间 O ( 1 ) O(1) O(1)。