O(n): Sliding window:
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int len = nums.size(); if (len == 0) return 0; int w = INT_MAX; int i = 0, j = 0; int sum = nums[0]; while (i <= j && j < len) { if (sum >= s) { w = std::min(w, j - i + 1); sum -= nums[i++]; // shrink } else // sum < s { j++; // expand if (j < len) sum += nums[j]; } } return w == INT_MAX ? 0 : w; } };
O(nlgn) - this is the punch line of this problem
https://leetcode.com/discuss/35335/o-nlgn-is-not-that-easy-here-is-my-java-code
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { int len = nums.size(); if (len == 0) return 0; // sums[i] : number sum from 0...i vector<int> sums(len, 0); sums[0] = nums[0]; for (int i = 1; i < len; i++) sums[i] = sums[i - 1] + nums[i]; if (sums.back() < s) return 0; int w = INT_MAX; for (int i = 0; i < len; i++) { // for each sum[i], find which k that, sum[k] - sum[i] + nums[i] >= s // that is, sum of num[i..k] int l = i; int r = len - 1; while (l <= r) { int mid = l + (r - l) / 2; if (sums[mid] - sums[i] + nums[i] == s) { l = mid; break; } else if (sums[mid] - sums[i] + nums[i] < s) { l = mid + 1; } else { r = mid - 1; } } if (l >= len) break; w = std::min(w, l - i + 1); } return w == INT_MAX ? 0 : w; } };