- Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn’t one, return -1 instead.
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.
Challenge
If you have figured out the O(nlog n) solution, try coding another solution of which the time complexity is O(n).
思路:同向双指针
注意:
- 凡是题目提到子串,子数组之类的,多考虑双指针(可能同向,也可能反向);
- 子串之类的题目有单调性,即超过某个就都满足
左边不行右边行 - 最短子串, 如此题
左边行右边不行 - 最长子串, 如Longest Substring Without Repeating Characters ??? - 同向双指针模板:右指针用for loop, 左指针嵌在for loop里面用while loop。满足条件时更新最大/小值,移动左指针并更新sum。
- 注意while loop的条件是 sum>=s,即==s的情况也必须考虑。LintCode 386的while loop也是一样。
代码如下:
class Solution {
public:
/**
* @param nums: an array of integers
* @param s: An integer
* @return: an integer representing the minimum size of subarray
*/
int minimumSize(vector<int> &nums, int s) {
int len = nums.size();
if (len == 0) return -1;
int left = 0;
int minLen = INT_MAX;
int sum = 0;
for (int right = 0; right < len; ++right) {
sum += nums[right];
while (sum >= s) { //注意这里是>=s,即==s的情况也考虑
minLen = min(minLen, right - left + 1);
sum -= nums[left];
left++;
}
}
return (minLen == INT_MAX) ? -1 : minLen;
}
};
二刷:
class Solution {
public:
/**
* @param nums: an array of integers
* @param s: An integer
* @return: an integer representing the minimum size of subarray
*/
int minimumSize(vector<int> &nums, int s) {
int n = nums.size();
int left = 0, right = 0;
int sum = 0, res = INT_MAX;
while (right < n) {
sum += nums[right];
right++;
while (sum >= s) {
res = min(res, right - left);
sum -= nums[left];
left++;
}
}
return res == INT_MAX ? -1 : res;
}
};