classSolution: defminSubArrayLen(self, target: int, nums: List[int]) -> int: from math import inf ans = inf left = 0 s = 0 for right, x inenumerate(nums): s += x while s >= target: ans = min(ans, right - left + 1) s -= nums[left] left += 1 return ans if ans != inf else0
C++
双指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intminSubArrayLen(int target, vector<int>& nums){ int ans = nums.size() + 1; int s = 0; int left = 0; for(int right = 0; right < nums.size(); right++) { s += nums[right]; while (s - nums[left] >= target) { s -= nums[left]; left += 1; } if (s >= target) { ans = min(ans, right - left + 1); } } return ans == nums.size() + 1 ? 0 : ans; } };