标签:
The problem statement has stated that there is both an O(n) and O(nlogn) solution to this problem. Let‘s see the O(n) solution first (taken from this link), which is pretty clever and short.
1 class Solution { 2 public: 3 int minSubArrayLen(int s, vector<int>& nums) { 4 int start = 0, sum = 0, minlen = INT_MAX; 5 for (int i = 0; i < (int)nums.size(); i++) { 6 sum += nums[i]; 7 while (sum >= s) { 8 minlen = min(minlen, i - start + 1); 9 sum -= nums[start++]; 10 } 11 } 12 return minlen == INT_MAX ? 0 : minlen; 13 } 14 };
Well, you may wonder how can it be O(n) since it contains an inner while loop. Well, the key is that the while loop executes at most once for each starting position start. Then start is increased by 1 and the while loop moves to the next element. Thus the inner while loop runs at most O(n) times during the whole for loop from 0 to nums.size() - 1. Thus both the for loop and while loop has O(n) time complexity in total and the overall running time is O(n).
There is also an O(n) solution in this link, which is easier to understand and prove it is O(n). I have rewritten it below.
1 class Solution { 2 public: 3 int minSubArrayLen(int s, vector<int>& nums) { 4 int n = nums.size(); 5 int left = 0, right = 0, sum = 0, minlen = INT_MAX; 6 while (right < n) { 7 do sum += nums[right++]; 8 while (right < n && sum < s); 9 while (left < right && sum - nums[left] >= s) 10 sum -= nums[left++]; 11 if (sum >= s) minlen = min(minlen, right - left); 12 } 13 return minlen == INT_MAX ? 0 : minlen; 14 } 15 };
[LeetCode] Minimum Size Subarray Sum
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4600467.html