题目:
思路1:暴力循环
class Solution {
public:int minSubArrayLen(int target, vector<int>& nums) {int len = INT_MAX;for(int i=0;i<nums.size();++i){int sum = 0;for(int j=i;j<nums.size();++j){sum+=nums[j];if(sum>=target){len = min(len,j - i + 1);break;}}}return len==INT_MAX ? 0:len;}
};
理论上可以解,但现在leetcode数据更新了,时间会超时
思路2:双指针(滑动窗口)
class Solution {
public:int minSubArrayLen(int target, vector<int>& nums) {int len = INT_MAX;int left = 0;int sum = 0;for(int right = 0;right<nums.size();++right){sum += nums[right];while(sum >= target){int subLen = right - left + 1;len = min(subLen,len);sum -= nums[left];left++;}}return len == INT_MAX ? 0 : len;}
};