209. Minimum Size Subarray Sum

来源:互联网 发布:coc防空火箭升级数据 编辑:程序博客网 时间:2024/06/05 04:21

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.

click to show more practice.

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).


双指针滑动窗口解法。

核心思想是:首先满足sum>=s这个目标,为了满足这个目标,可能窗口的右端需要不断地移动。在满足了这个目标以后,开始”尽可能“地移动窗口左端的指针,在这个过程中可以记录下最短的满足要求的区间长度。

 public static int minSubArrayLen(int s, int[] nums){int len=nums.length;if(len<1)return 0;boolean isfail=true;int start=0;int end=0;int minsub=Integer.MAX_VALUE;int sum=0;for(int i=0;i<len;i++){sum+=nums[i];if(sum>=s){isfail=false;end=i;break;}}if(isfail)return 0;minsub=Math.min(minsub, end-start+1);while(end<len){while(end<len-1&&sum<s){end++;sum+=nums[end];}while(start<end&&sum-nums[start]>=s){sum-=nums[start];start++;}if(start==len)break;if(sum>=s)minsub=Math.min(minsub, end-start+1);sum-=nums[start];start++;}return minsub;}


0 0
原创粉丝点击