这题和之前做的一个滴滴魔法石题很像。解题步骤也基本一致 由于最低运力肯定是大于等于最大货物重量,小于等于所有货物相加的重量。所以直接二分查找 复杂度应该是NlogN
class Solution { public int shipWithinDays(int[] weights, int D) { int total = 0; int max = 0; for (int weight : weights) { total+=weight; max = Math.max(weight,max); } int left = max,right = total; //二分法查看是否满足 while (left<right){ int mid = (left+right)/2; if (check(weights, D, mid)){ right = mid; }else { left = mid+1; } } return left; } public boolean check(int[] weights,int D,int mid){ int s = 0; int tpt = 0; for (int i = 0; i < weights.length; i++) { int t = weights[i]; tpt+=t; if (tpt == mid){ s++; tpt = 0; }else if (tpt > mid){ s++; tpt = t; } if (s >D){ return false; } if (i == weights.length-1 && tpt != 0){ s++; } } return s<=D; } }