|
1 | | -package io.github.dunwu.algorithm.array; |
| 1 | +package io.github.dunwu.algorithm.array.bsearch; |
2 | 2 |
|
3 | 3 | import org.junit.jupiter.api.Assertions; |
4 | 4 |
|
5 | 5 | import java.lang.reflect.InvocationTargetException; |
| 6 | +import java.util.Arrays; |
6 | 7 |
|
7 | 8 | /** |
8 | 9 | * <a href="https://leetcode.cn/problems/capacity-to-ship-packages-within-d-days/">1011. 在 D 天内送达包裹的能力</a> |
|
13 | 14 | public class 在D天内送达包裹的能力 { |
14 | 15 |
|
15 | 16 | public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { |
| 17 | + |
| 18 | + // Assertions.assertEquals(5, f(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 15)); |
| 19 | + // Assertions.assertEquals(3, f(new int[] { 3, 2, 2, 4, 1, 4 }, 6)); |
| 20 | + // Assertions.assertEquals(4, f(new int[] { 1, 2, 3, 1, 1 }, 3)); |
| 21 | + |
16 | 22 | Assertions.assertEquals(15, shipWithinDays(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5)); |
17 | 23 | Assertions.assertEquals(6, shipWithinDays(new int[] { 3, 2, 2, 4, 1, 4 }, 3)); |
18 | 24 | Assertions.assertEquals(3, shipWithinDays(new int[] { 1, 2, 3, 1, 1 }, 4)); |
19 | 25 | } |
20 | 26 |
|
21 | 27 | public static int shipWithinDays(int[] weights, int days) { |
22 | | - int left = 0, right = 1; |
| 28 | + int left = 0; |
| 29 | + int right = 0; |
| 30 | + for (int w : weights) { |
| 31 | + left = Math.max(left, w); |
| 32 | + right += w; |
| 33 | + } |
| 34 | + |
23 | 35 | while (left <= right) { |
24 | 36 | int mid = left + (right - left) / 2; |
25 | 37 | if (f(weights, mid) == days) { |
26 | | - // 搜索左侧边界,则需要收缩右侧边界 |
27 | | - right = mid; |
| 38 | + right = mid - 1; |
28 | 39 | } else if (f(weights, mid) < days) { |
29 | | - // 需要让 f(x) 的返回值大一些 |
30 | | - right = mid; |
| 40 | + right = mid - 1; |
31 | 41 | } else if (f(weights, mid) > days) { |
32 | | - // 需要让 f(x) 的返回值小一些 |
33 | 42 | left = mid + 1; |
34 | 43 | } |
35 | 44 | } |
36 | 45 | return left; |
37 | 46 | } |
38 | 47 |
|
39 | | - public static long f(int[] weights, int x) { |
40 | | - long days = 0; |
| 48 | + public static int f(int[] weights, int x) { |
| 49 | + int days = 0; |
41 | 50 | for (int i = 0; i < weights.length; ) { |
42 | 51 | int cap = x; |
43 | 52 | while (i < weights.length) { |
|
0 commit comments