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.
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.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
/*
* 双指针sta和end,大循环是每次end++,比较两个指针间所有数的和和target的大小,大于的话进小循环,不断sta++,知道小于,每次都更新res
* 两指针之间所有数的和的计算,一开始想到的是每次指针变动的时候都for循环进行相加,后来看了别人的方法,发现不用每次都重新加
* 只要当end++后cur加上当前值,sta++前cur减去当前值就行,有点像回溯
* 注意会有全部相加都小于的情况,最后要单独判断*/
public int minSubArrayLen(int s, int[] nums) { //双指针 int sta = 0; int end = 0; //length int res = nums.length + 1; //当前的和 int cur = 0; //大循环 while (end < nums.length) { cur += nums[end]; //小循环 while (cur >= s) { res = Math.min(res,end - sta + 1); cur -= nums[sta]; sta ++; } end++; } //特殊情况判断 if (res == nums.length + 1) return 0; return res; }