classSolution { publicintminEatingSpeed(int[] piles, int h) { intn= piles.length; intmax=0; for (int x : piles) { max = Math.max(max, x); } intl=1, r = max; while (l < r) { intmid= l + r >> 1; if (check(piles, mid, h)) r = mid; else l = mid + 1; } return l; } publicbooleancheck(int[] ps, int t, int h) { inttime=0; for (int x : ps) { time += (x + t - 1) / t; } return time <= h; } }
classSolution { publicintshipWithinDays(int[] weights, int days) { intn= weights.length; intsum=0; intmax=0; for (inti=0; i < n; ++i) { max = Math.max(max, weights[i]); sum += weights[i]; } intl= max, r = sum; while (l < r) { intmid= l + r >> 1; // if (check(weights, mid, days)) r = mid; else l = mid + 1; } return l; }
publicbooleancheck(int[] ws, int t, int days) { intlen= ws.length; intsum= ws[0]; intcnt=0; // 统计天数 for (inti=1; i < len; sum = 0, ++cnt) { while (i < len && sum + ws[i] <= t) { sum += ws[i]; i++; } } return cnt <= days; // 小于规定时限则认为可以成功运送 } }
classSolution { publicintsplitArray(int[] nums, int m) { intl=0, r = (int) 1e9;
while (l < r) { intmid= l + r >> 1; if (check(nums, mid, m)) r = mid; else l = mid + 1; } return l; } booleancheck(int[] q, int tmp, int m) { if (q[0] > tmp) returnfalse; intcnt=0; intn= q.length; for (inti=1, sum = q[0]; i < n; sum = 0, ++cnt) { if (q[i] > tmp) returnfalse; while (i < n && sum + q[i] <= tmp) { sum += q[i]; i++; } } return cnt <= m; } }
classSolution { publicintmaximizeSweetness(int[] sweetness, int k) { // intl=0, r = (int) 1e9; intans=0; while (l < r) { intmid= l + r + 1 >> 1; if (check(sweetness, mid, k + 1)) { l = mid; } else r = mid - 1; } return l; } booleancheck(int[] q, int curSweetness, int m) { intcnt=0; intn= q.length; intsum=0; for (inti=0; i < n; ++i) { sum += q[i]; if (sum >= curSweetness) { sum = 0; cnt++; } } return cnt >= m; } }
classSolution { publicintmaxValue(int n, int idx, int maxSum) { // x-1, x, x-1, x-2, x-3, x-4; // idx // k = n - idx - 1 // 二分查找 x intl=1, r = (int)1e9; while (l < r) { intmid= l + ((r - l + 1) >> 1); if (check(idx, mid, n, maxSum)) l = mid; else r = mid - 1; } return l;
}
booleancheck(int idx, int x, int n, int maxSum) { // 分两种情况 // case1: x >= idx + 1 // 例如 :2 3 4 [5] 4 3 2 // case2: x < idx + 1 // 例如 :1 1 2 [3] 2 1 1 由于元素均为正整数(>= 1),因此减少到1后不能继续减少 // 此时,以左侧为例,所求为1到x-1的总和,再加上1的个数 longleft= x - idx >= 1 ? (long)(x - 1 + x - idx) * idx / 2 : (long)(x - 1) * x / 2 + (idx + 1 - x); intk= n - idx - 1; longright= x - k >= 1 ? (long)(x - 1 + x - k) * k / 2 : (long)(x - 1) * x / 2 + (k + 1 - x); return left + right + x <= maxSum; } }