题目描述:
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(n) solution, try coding another solution of which the time complexity is O(n log n).
这题还是用two pointers的方法,既然要算subarray的和,那么用一个presum去记录每个index之前的和,可以省去重复计算subarray和的麻烦。用2个pointers,都从头开始,如果subsum >= s,那么l向右移看看有没有更短的答案;反之,r向右移拉长subarray,看看有没有符合条件的答案。
Mycode(AC = 298ms):
class Solution {
public:
/**
* @param nums: a vector of integers
* @param s: an integer
* @return: an integer representing the minimum size of subarray
*/
int minimumSize(vector<int> &nums, int s) {
// write your code here
if (nums.size() == 0) return -1;
// 0,2,5,6,8,12,15
// get presum
vector<int> presum(nums.size() + 1, 0);
for (int i = 1; i <= nums.size(); i++) {
presum[i] = presum[i - 1] + nums[i - 1];
}
// two pointers to find the min length
int l = 0, r = 1, minlen = INT_MAX;
while (r <= nums.size()) {
// if sum >= s, then increase l to find
// shorter answer
if (presum[r] - presum[l] >= s) {
minlen = min(minlen, r - l);
l++;
}
// if sum < s, then increase r to find answer
else {
r++;
}
}
return minlen == INT_MAX? -1 : minlen;
}
};