当前位置:网站首页>1011. 在 D 天内送达包裹的能力
1011. 在 D 天内送达包裹的能力
2022-07-20 22:24:00 【baixiaofei567】
很好的题,一开始想dfs爆搜的,还是直接看了三叶学姐的题解。
是一道二分查找的题,我们要找的是能在D天内送完的最小载重量。不考虑天数的情况下最小的载重量是足够运送最大货物的,最大载重量就是所有货物一天运完。
左边界就是max,有边界就是sum,对其进行二分,写一个check函数,这个很重要,对当前运力进行判断,这是我们二分缩小搜索范围的标准。check内部就是计算当前运力需要几天运完
如果运送天数<=D,mid不能扔,继续去左边找,看看能否找到更小的。如果>D,就要提升载重量,去右边找,而且mid不要了。
最后返回的r,因为我们控制<=的时候mid不丢弃变成r,当结束时,r是那个最小的解
class Solution {
public:
bool check(vector<int>& weights,int t,int D){
int day = 0;
for(int i = 0; i < weights.size();){
day++;
int sum = 0;
//没越界且没超过载重的情况下,可以运送
while(i < weights.size() && sum + weights[i] <= t){
sum += weights[i++];
}
}
return day <= D;
}
int shipWithinDays(vector<int>& weights, int D) {
//从最小运力和最大运力之间用二分找出运D天的
//如果当前运力运送的超过D天就去右边,小于等于去左边。为什么小于等于
//最后返回r,为什么
int l = 0, r = 0;
for(int x : weights){
l = max(l,x);
r += x;
}
while(l < r){
int mid = l + (r-l)/2;
if(check(weights,mid,D)){
r = mid;
}
else{
l = mid + 1;
}
}
//因为我们控制<=的时候mid不丢弃变成r,当结束时,r是那个最小的解
return r;
}
};
边栏推荐
- Redis内存模型讲解
- Jax calculation Selu function
- Ça marche! Jira + Zadig Implementation Requirements and R & D Process Tracking
- GAMES101图形学P11笔记(geometry2)
- Is Ping An Securities a state-owned enterprise? Is it safe to open an account?
- 我来告诉你,一个草根程序员如何逆袭,成功进入BAT!
- scala WordCount案例
- 即时分账系统对B2B电商业务的重要性?
- Beisen prospectus: the advantages of the track are prominent, and integration + medium and large customers are plus points
- LNMP------PHP7安装
猜你喜欢
随机推荐
Image of JZ27 binary tree
measureChildren的理解
使用MySQL,请用好 JSON 这张牌
Scala exercises student scores case
Redis内存模型讲解
Part 132 deletion in mapping
STM32串口屏学习
Known file name is the directory where the file is located
几种常用登录的调试方式
RS-485 communication
[leetcode] use bisection in unordered arrays
如何做好测试管理?
渗透测试成功的8个关键
Scala(二)IO流 读取文件和保存文件
@RequestBody注解转对象中驼峰格式的参数无法接收到数据的问题解决方法
按下Ctrl弹出一个对话框松开关闭此对话框,如何实现?
盛邦安全冲刺科创板:奇安信是其第一大客户(5587 万);其三年收入 4.6 亿、净利润 9504 万,研发投入 7846 万
Summary of APP page seconds open optimization~
39岁被裁+背房贷(没活路了)
Scala (II) IO stream read file and save file