classSolution{ publicintminSubArrayLen(int target, int[] nums){ int res = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) { int s = 0; for (int j = i; j < nums.length; j++) { s += nums[j]; if (s >= target) { res = Math.min(j - i + 1, res); break; } } } return res == Integer.MAX_VALUE ? 0 : res; } }
思路二
这种连续数组应该想到双指针,左右指针都指向开始的位置即left = right = 0,初始和为nums[0]
classSolution{ publicintminSubArrayLen(int target, int[] nums){ int left = 0; int right = 0; int s = nums[0]; int res = Integer.MAX_VALUE; while (right < nums.length) { if (s < target) { right += 1; if (right < nums.length) { s += nums[right]; }
} else { s -= nums[left]; res = Math.min(res, right - left + 1); left += 1; } } return res == Integer.MAX_VALUE ? 0 : res; } }
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution{ publicintminSubArrayLen(int target, int[] nums){ int res = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) { int s = 0; for (int j = i; j < nums.length; j++) { s += nums[j]; if (s >= target) { res = Math.min(j - i + 1, res); break; } } } return res == Integer.MAX_VALUE ? 0 : res; } }
classSolution{ publicintminSubArrayLen(int target, int[] nums){ int left = 0; int right = 0; int s = nums[0]; int res = Integer.MAX_VALUE; while (right < nums.length) { if (s < target) { right += 1; if (right < nums.length) { s += nums[right]; }
} else { s -= nums[left]; res = Math.min(res, right - left + 1); left += 1; } } return res == Integer.MAX_VALUE ? 0 : res; } }