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.

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

 

 1 public class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         if(nums==null||nums.length==0) return 0;
 4         int left = 0;
 5         int right = 0;
 6         int sum = 0;
 7         int count = Integer.MAX_VALUE;
 8         while(right<nums.length){
 9             sum+=nums[right];
10             while(sum>=s){
11                 count = Math.min(count,right-left+1);
12                 sum-=nums[left];
13                 left++;
14             }
15             right++;
16         }
17         return count==Integer.MAX_VALUE?0:count;
18     }
19 }
20 //the time couplexity could be O(n),the space complexity could be O(1);
 1 public class Solution {
 2     public int minSubArrayLen(int s, int[] nums) {
 3         int[] sums = new int[nums.length+1];
 4         for(int i=0;i<nums.length;i++){
 5             sums[i+1] = sums[i]+nums[i];
 6         }
 7         int min = Integer.MAX_VALUE;
 8         for(int i=0;i<sums.length;i++){
 9             int end = binarysearch(sums,i+1,sums.length-1,sums[i]+s);
10             if(end==sums.length) break;
11             if(end-i<min) min = end-i;
12         }
13         return min==Integer.MAX_VALUE?0:min;
14     }
15     public int binarysearch(int[] sums,int left,int right,int target){
16         while(left<=right){
17             int mid = left+(right-left)/2;
18             if(sums[mid]<target){
19                 left = mid+1;
20             }else{
21                 right = mid-1;
22             }
23         }
24         return left;
25     }
26 }
27 // the time complexity could be nlogn,the space complexity could be O(1);

 

 

 

posted @ 2017-03-02 11:55  CodesKiller  阅读(129)  评论(0编辑  收藏  举报