209. 长度最小的子数组
https://leetcode.cn/problems/minimum-size-subarray-sum/?envType=study-plan-v2&envId=top-interview-150
思路
三种方法中,具有最优时间复杂度的方案
滑动窗口
设置 start=0 end=0
执行循环:
end向后探测,直到sum值大于等于target,更新最优长度
然后start向前探测,探测过程中,如果sum仍然大于等于target,更新最优长度,
start向前探测,直到sum小于target时候停止。
此过程很像毛毛虫先前蠕动行为, 可以称之为毛毛虫行走法。
https://leetcode.cn/problems/minimum-size-subarray-sum/solutions/305704/chang-du-zui-xiao-de-zi-shu-zu-by-leetcode-solutio/?envType=study-plan-v2&envId=top-interview-150
Code
class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { /* [start, end] 以此为窗口探测总和>=target的最小连续序列长度 */ int start = 0; int end = 0; long long sum = nums[0]; int minlen = 1e5+5; while(start<=end && end<nums.size()){ // cout << "------------------------------------------" << endl; // cout << "BEGIN ====> start = " << start << " end=" << end << endl; // if (sum >= target){ // minlen = min(minlen, end-start+1); // cout << "update1 minlen = " << minlen << endl; // } do { if (sum >= target){ minlen = min(minlen, end-start+1); // cout << "update2 minlen = " << minlen << endl; break; } end++; if (end >= nums.size()){ break; } sum += nums[end]; } while(true); if (end >= nums.size()){ break; } // cout << "AFTER ENLARGE end ====> start = " << start << " end=" << end << endl; do { if (sum < target){ break; } else if (sum >= target){ minlen = min(minlen, end-start+1); // cout << "update1 minlen = " << minlen << endl; } if (start<end){ sum -= nums[start]; start++; } else { break; } } while(true); // cout << "AFTER ENLARGE start ====> start = " << start << " end=" << end << endl; // cout << "minlen = " << minlen << endl; // cout << "END ====> start = " << start << " end=" << end << endl; if (minlen == 1){ break; } } return minlen==1e5+5?0:minlen; } };
标签:end,target,minlen,209,sum,start,int,数组,长度 From: https://www.cnblogs.com/lightsong/p/18081737