classSolution { public: intminSubArrayLen(int target, vector<int>& nums){ int result=INT32_MAX; int n; 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) { n = j - i + 1; result = result < n ? result : n; } } } if (result == INT32_MAX) { return0; } else return result; } };
classSolution { public: intminSubArrayLen(int target, vector<int>& nums){ int sum = 0; int result = INT32_MAX; int i = 0; for (int j = 0; j < nums.size(); j++) { sum += nums[j]; while (sum >= target) { int n = j - i + 1; result = result < n?result:n; sum -= nums[i++]; } } if (result == INT32_MAX) { return0; } else return result; } };
关键在于
1 2 3 4 5
while (sum >= target) { int n = j - i + 1; result = result < n?result:n; sum -= nums[i++]; }