Saturday, July 2, 2016

209. Minimum Size Subarray Sum

We can have two pointers. One scans the array and the other keeps the start position of a subarray that is supposed to have sum larger or equal to the target. One the subarray's sum is larger or equal to the target, we save the length of subarray and move the start point forward until we reach the position that the sum of the subarray is less than the target. After that, we continue scanning the array again. The total running time will be O(2n).

1:  class Solution {  
2:  public:  
3:    int minSubArrayLen(int s, vector<int>& nums) {  
4:      int start = 0, minLen = INT_MAX, sum = 0;  
5:      for (int i = 0; i < nums.size(); i++) {  
6:        sum += nums[i];  
7:        while (s <= sum) {  
8:          minLen = min(minLen, i-start+1);  
9:          sum -= nums[start++];  
10:        }  
11:      }  
12:      return minLen == INT_MAX ? 0 : minLen;  
13:    }  
14:  };  

No comments:

Post a Comment