209. Minimum Size Subarray Sum
Medium
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
题意
给定n个正整数组成的数组nums和一个整数s,求nums的最短连续子列,使得子列之和大于等于s
思路
双指针法。维护两个指针l和r,分别指向子列左端和右端,单调地从左向右移动,每个元素最多被l访问一次被r访问一次,时间复杂度为O(n).
代码
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
int n = nums.size();
if (n == 0) {
return 0;
}
int l = 0, r = l, cur = 0, len = std::numeric_limits<int>::max();
while (true) {
while (l < r && cur >= s) {
len = std::min(len, r - l);
cur -= nums[l++];
}
while (r < n && cur < s) {
cur += nums[r++];
}
if (cur < s) {
break;
}
len = std::min(len, r - l);
}
return len == std::numeric_limits<int>::max()? 0: len;
}
};