1011. 在 D 天内送达包裹的能力
思路:二分查找 python代码如下 但是比思路3快上一倍
1 class Solution(object): 2 def shipWithinDays(self, weights, D): 3 r, l = 100000, 1 # 题目给定D的最大值是50000,所以r的·初始值必须大于100000 4 while (l + 1 )!= r: 5 mid = (r + l) // 2 6 if self.f(mid, D, weights): 7 r = mid 8 else: 9 l = mid 10 return r 11 12 def f(self, x, D, weights): 13 j = 0 14 for i in range(D): 15 t = x 16 while j < len(weights) and t >= weights[j]: 17 t -= weights[j] 18 j += 1 19 if j == len(weights): 20 return True 21 return False
c++的二分查找 但是比思路快上9倍
1 class Solution { 2 public: 3 bool C(int x,int D,vector<int>& weights){ 4 int j=0; 5 for(int i=0;i<D;++i){ 6 int t=x; 7 while(j<weights.size()&&t>=weights[j]){ 8 t-=weights[j++]; 9 } 10 if(j==weights.size())return true; 11 } 12 return false; 13 } 14 int shipWithinDays(vector<int>& weights, int D) { 15 int r=100000,l=1,mid; 16 while(l+1!=r){ 17 mid=(r+l)/2; 18 if(C(mid,D,weights)){ 19 r=mid; 20 }else{ 21 l=mid; 22 } 23 //cout<<l<<" "<<r<<" "<<mid<<endl; 24 } 25 return r; 26 } 27 };
思路·3:python的贪心实现
1 class Solution(object): 2 def shipWithinDays(self, weights, D): 3 """ 4 :type weights: List[int] 5 :type D: int 6 :rtype: int 7 """ 8 res=max(sum(weights)//D,max(weights)) 9 while True: 10 n=1 11 temp=0 12 for each in weights: 13 if temp+each<=res: 14 temp+=each 15 else: 16 temp=each 17 n+=1 18 if n>D: 19 break 20 if n<=D: 21 return res 22 else: 23 res+=1 24 return res