题目
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.
解法
滑动窗口解决,通过动态控制窗口的和,使窗口和在第一层循环中始终处于小于s的状态,而在第二层循环中,当窗口和大于s的时候,则对s进行逼近,每次逼近后进行一次判断,则可得出最短距离。
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int j = 0,result = 0,sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
while (sum >= s) {
//因为result初值为0
if(result != 0) result = Math.min(result, i + 1 - j);
else result = i + 1 - j;
//减走
sum -= nums[j++];
}
}
return result;
}
}