https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
传送带要在D天内把所有货物传送完,但是传送带每天有传送容量的限制,问保证货物在D天内传送完的最小容量限制。货物重量以weights[]给出。
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
一开始想从weights来求最小容量,发现无论如何都不能达到线性时间复杂度。想了好久,突然想到可以二分最小容量,然后对容量验证是否能达到要求。
此外,容量初始最小值为单个货物的最大重量,容量最大值为所有货物重量加和。
class Solution { public: bool can(vector<int>& weights, int D, int maxn) { int temp=0,i=0,day=0; while(i<weights.size()) { while(i<weights.size() && temp+weights[i]<=maxn) { temp+=weights[i]; i++; } if(i<weights.size()&&temp+weights[i]>maxn) { temp=0; day++; } if(i>=weights.size() && temp<=maxn && temp>0) day++; } return day<=D; } int shipWithinDays(vector<int>& weights, int D) { int sum_weight=0, max_item_weight=INT_MIN; for(int i=0; i<weights.size(); i++) { sum_weight+=weights[i]; max_item_weight = max(max_item_weight, weights[i]); } int low=max_item_weight, high=sum_weight, res=0; while(low<=high) { int mid = (low+high)/2; if(can(weights,D,mid)) { res=mid; high = mid-1; } else low = mid+1; } return res; } };