1 //跟LeetCode3类似 2 class Solution 3 { 4 public: 5 int minSubArrayLen(int s, vector<int>& nums) 6 { 7 //如果为空,直接返回0 8 if(nums.empty()) return 0; 9 int res = 0; 10 for(auto a : nums) res += a; 11 //如果数组总和小于s,直接返回0 12 if(res < s) return 0; 13 14 res = 0; 15 int len = INT_MAX; 16 int n = nums.size(); 17 int begin = 0; 18 for(int i = 0;i < n;i ++) 19 { 20 res += nums[i]; 21 while(res >= s) 22 { 23 len = min(len,i - begin + 1); 24 res -= nums[begin++]; 25 } 26 } 27 len = min(len,n - begin + 1); 28 return len; 29 } 30 };