# 209. Minimum Size Subarray Sum

lpy1990
Given an array of n positive integers and a positive integer s, find
the minimal length of a contiguous subarray of which the sum ≥ s. If
there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray
[4,3] has the minimal length under the problem constraint.

## 解法 BF

### 代码

``````class Solution {
public int minSubArrayLen(int s, int[] nums) {
int res = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
int sum = 0;
for (int j = i; j < nums.length; j++) {
sum+= nums[j];
if (sum >= s) {
res = Math.min(j -i + 1, res);
break;
}
}
}
return (res == Integer.MAX_VALUE)? 0:res;

}
}``````

## 解法 双指针

### 代码

``````class Solution {
public int minSubArrayLen(int s, int[] nums) {
int left = 0, right = 0, sum = 0, res = Integer.MAX_VALUE;
while (left <=right && right <= nums.length) {
if (sum < s) {
if (right <nums.length) {
sum += nums[right];
}
right++;
} else {
res = Math.min(res, right - left);
sum-= nums[left];
left++;
}
}
return (res == Integer.MAX_VALUE)? 0:res;
}
}``````

26 声望
10 粉丝
0 条评论