sum += nums[right];此处更新的是窗尾,我错误写成sum += nums[left];
int sum,left,subLen = 0;这样初始化在leetcode中报错不知道为什么
复杂度
时间复杂度:
$O(n)$
空间复杂度:
$O(1)$
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intminSubArrayLen(int target, vector<int>& nums){ int result = INT32_MAX; int sum = 0,left = 0,subLen = 0; for(int right = 0; right < nums.size(); right++){ //窗尾前移 sum += nums[right]; while(sum >= target) { subLen = right - left + 1; result = subLen < result ? subLen : result; sum -= nums[left]; left ++; //窗头前移 } } return result == INT32_MAX ? 0 :result; } };