leetcode 1014. 在 D 天内送达包裹的能力

这道题实际上可以应用二分查找算法来求解,但是我周赛的时候死活没想到;看了前几名的代码才反应过来;

于是自己重写(其实就是复制了一遍)大神的代码,思路很清晰,一共两个函数,主函数是二分查找的代码,check函数负责判断mid=(left+right)/2处的值是否符合要求,若符合,将右边界更新为mid,若不符合,说明当前每天限度过低,更新左边界为mid+1;

C++代码:

 1 class Solution {
 2 public:
 3     int shipWithinDays(vector<int>& weights, int D) {
 4         int r = 0;
 5         for(auto w : weights) r+=w;
 6         int l = 1;
 7         cout<<"r: "<<r<<endl;
 8         while(l<r) {
 9             cout<<"l: "<<l;
10             int m = (l+r)>>1;//
11             cout<<" , m: "<<m;
12             if(check(weights, D, m)) r=m;
13             else l=m+1;
14             cout<<"  ,r: "<<r<<"  "<<endl;
15         }
16         return r;
17     }
18     bool check(vector<int>& weights, int D, int c) {
19         int cur = 0;
20         int n = weights.size();
21         for(int i=0; i<D; ++i) {
22             int t = c;
23             cout<<" t: "<<t<<" ";
24             while(cur<n && weights[cur]<=t) {
25                 t-=weights[cur++];
26                 cout<<t<<" ";
27             }
28             cout<<"  cur: "<<cur<<" ";
29             if(cur==n) return true;
30         }
31         return false;
32     }
33 };

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10549170.html