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 0 instead.
For 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.
思路:用start, end两个游标来记录范围,sum < s end就向后走, s >= sum start就向后走。
我写的代码没有大神的逻辑清晰,先上大神的。
int minSubArrayLen(int s, vector<int>& nums) { int firstPos = 0, sum = 0, minLength = INT_MAX; for(int i = 0; i<nums.size(); i++) { //i即end游标 对所有end游标循环 sum += nums[i]; while(sum >= s) { //对每个end游标的start游标循环 firstPos即为start游标 只有s >= sum 时才把start向后移 minLength = min(minLength, i - firstPos + 1); sum -= nums[firstPos++]; } } return minLength == INT_MAX? 0 : minLength; //没找到s >= sum 时返回0 }
我的代码乱一点,但是也AC了。
int minSubArrayLen(int s, vector<int>& nums) { int start = 0, end = 0; int sum = 0; int minLength = nums.size() + 1; while(end <= nums.size()) //有等于是因为结尾到最后面时 起始点还可能移动 { if(sum < s) { if(end == nums.size()) break; sum += nums[end++]; } else { minLength = (minLength < (end - start)) ? minLength : (end - start); sum -= nums[start++]; } } minLength = (minLength == nums.size() + 1) ? 0 : minLength; //没找到符合条件的子序列 返回0 return minLength; }
时间: 2024-10-13 15:37:06