author: Blankj blog : http://blankj.com time : 2020/06/30 desc :
| 11 | * </pre> |
| 12 | */ |
| 13 | public class Solution { |
| 14 | // public int minSubArrayLen(int s, int[] nums) { |
| 15 | // int ans = Integer.MAX_VALUE; |
| 16 | // for (int i = 0; i < nums.length; i++) { |
| 17 | // int sum = nums[i]; |
| 18 | // if (sum >= s) { |
| 19 | // return 1; |
| 20 | // } |
| 21 | // for (int j = i + 1; j < nums.length; j++) { |
| 22 | // sum += nums[j]; |
| 23 | // if (sum >= s) { |
| 24 | // ans = Math.min(ans, j - i + 1); |
| 25 | // break; |
| 26 | // } |
| 27 | // } |
| 28 | // } |
| 29 | // return ans == Integer.MAX_VALUE ? 0 : ans; |
| 30 | // } |
| 31 | |
| 32 | // public int minSubArrayLen(int s, int[] nums) { |
| 33 | // int left = 0, right = 0, sum = 0, ans = Integer.MAX_VALUE; |
| 34 | // while (right < nums.length) { |
| 35 | // sum += nums[right++]; // 向右扩大窗口 |
| 36 | // while (sum >= s) { // 如果不小于 s,则收缩窗口左边界 |
| 37 | // ans = Math.min(ans, right - left);// 更新结果 |
| 38 | // sum -= nums[left++]; // 向左缩小窗口 |
| 39 | // } |
| 40 | // } |
| 41 | // return ans == Integer.MAX_VALUE ? 0 : ans; |
| 42 | // } |
| 43 | |
| 44 | public int minSubArrayLen(int s, int[] nums) { |
| 45 | int ans = Integer.MAX_VALUE; |
| 46 | int[] sums = new int[nums.length + 1]; |
| 47 | for (int i = 0; i < nums.length; i++) { |
| 48 | sums[i + 1] = sums[i] + nums[i]; |
| 49 | } |
| 50 | for (int i = 0; i < nums.length; i++) { |
| 51 | int target = s + sums[i]; // 确定要搜索的目标值 |
| 52 | // Java 二分查找 Arrays.binarySearch 如果找到就会返回该元素的索引; |
| 53 | // 如果没找到就会返回一个负数,这个负数取反之后再减一就是查找的值应该在数组中的位置; |
| 54 | // 例如 [-1, 0, 1, 5] 中二分查找 2,其返回值就是 -4,其 -(-4) - 1 = 3,所以 2 这个元素插入到数组的索引就是 3 |
| 55 | int bound = Arrays.binarySearch(sums, target); |
| 56 | if (bound < 0) { |
| 57 | bound = -bound - 1; |
| 58 | } |
| 59 | if (bound < sums.length) { // 当 bound 确定插入点不在 sums 数组的最后面时,说明不小于 target 的值了 |
| 60 | ans = Math.min(ans, bound - i); |
| 61 | } |
| 62 | } |
| 63 | return ans == Integer.MAX_VALUE ? 0 : ans; |
| 64 | } |
| 65 | |
| 66 | public static void main(String[] args) { |
| 67 | Solution solution = new Solution(); |
| 68 | System.out.println(solution.minSubArrayLen(7, new int[]{2, 3, 1, 2, 4, 3})); |
| 69 | } |
| 70 | } |
nothing calls this directly
no outgoing calls
no test coverage detected