forked from yuanguangxin/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
40 lines (38 loc) · 1.01 KB
/
Solution.java
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
40
package 双指针遍历.q209_长度最小的子数组;
/**
* 两个指针滑动窗口o(n)
*/
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
int sum = 0;
int i = 0;
int k = 0;
int min = Integer.MAX_VALUE;
while (true) {
if (k == nums.length && i == nums.length) {
break;
}
if (sum == s) {
min = Math.min(k - i, min);
if (k < nums.length) {
sum += nums[k];
k++;
} else {
sum -= nums[i];
i++;
}
} else if (sum < s) {
if (k == nums.length) {
break;
}
sum += nums[k];
k++;
} else {
min = Math.min(k - i, min);
sum -= nums[i];
i++;
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}