209. Minimum Size Subarray Sum

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
      int cur_sum = 0; 
      int min_len = Integer.MAX_VALUE;
      int n = nums.length;
      
      int start = 0;
      int end = 0;
      while(end < n){
        while( cur_sum < s && end < n){
         cur_sum = cur_sum + nums[end];
         end++;
        }
        while( cur_sum >= s && start <= end){
         min_len = Math.min( min_len, end - start );
         cur_sum = cur_sum - nums[start];
         start++;
        }
      }
      if(min_len != Integer.MAX_VALUE){
        return min_len;
      }else{
        return 0;
      }
    }
}

 

public int minSubArrayLen(int s, int[] a) {
  if (a == null || a.length == 0)
    return 0;
  
  int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
  
  while (j < a.length) {
    sum += a[j++];
    
    while (sum >= s) {
      min = Math.min(min, j - i);
      sum -= a[i++];
    }
  }
  
  return min == Integer.MAX_VALUE ? 0 : min;
}

 

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.

Example: 

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). 

 

posted on 2018-07-18 09:03  猪猪&#128055;  阅读(101)  评论(0)    收藏  举报

导航