209. Minimum Size Subarray Sum

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.

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

题意:获取最短子串的长度,使其总和大于等于给定的值s
 
 1     public int minSubArrayLen(int s, int[] nums) {
 2 //        定义两个指针left和i,分别记录子数组的左右的边界位置,每次i右移1位,就将结果累加到sum中。
 3 //        找出left到i范围内sum大于s时最小的长度(i-left+1),然后将left右移,同时在sum中去除nums[left]的值
 4         int res = Integer.MAX_VALUE, left = 0, sum = 0;
 5         for (int i = 0; i < nums.length; ++i) {
 6             sum += nums[i];
 7             while (left <= i && sum >= s) {
 8                 res = Math.min(res, i - left + 1);
 9                 sum -= nums[left++];
10             }
11         }
12         return res == Integer.MAX_VALUE ? 0 : res;        
13     }

 

posted @ 2017-10-16 16:26  daniel456  阅读(98)  评论(0编辑  收藏  举报