Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3]
and s = 7
,
the subarray [4,3]
has the minimal length under the problem constraint.
[思路]
兩個指針, start end, end向後走,直到 sum 大於 s. 然後start向後, 直到sum 小於s. 同時更新 min值.
public class Solution { //1,1,4 public int minSubArrayLen(int s, int[] nums) { //init check int start = 0; int end = 0; int sum = 0; int min = Integer.MAX_VALUE; while(start=s && start<=end) { min = Math.min(min, end-start); sum -= nums[start++]; } } return min==Integer.MAX_VALUE ? 0 : min; } }