1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public static int minSubArrayLen(int target, int[] nums) {
// 获取原数组长度
int n = nums.length;
int[] preSum = new int[n + 1];
preSum[0] = 0;
for (int i = 1; i <= n; i++) {
preSum[i] = preSum[i - 1] + nums[i - 1];
}
int left = 0;
int right = 1;
int ans = Integer.MAX_VALUE;
while (right < preSum.length) {
// 当前窗口的和 >= target
if (preSum[right] - preSum[left] >= target) {
// 更新最小长度
ans = Math.min(right - left, ans);
// 既然当前窗口已经满足条件,尝试去掉左边元素,看能否找到更短的窗口
left++;
}
else if (preSum[right] - preSum[left] < target) {
// 当前窗口不满足条件,和太小了
// 右指针右移,将更多元素包含进窗口
right++;
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
|