Solution 1
因为是寻找最优的连续区间,我们可以通过双指针维护这个考察区间,并寻找最优解。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入数组的长度,一次线性遍历
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int left = 0, right = 0;
int tempSum = 0;
int ans = INT_MAX;
while (right < nums.size()) {
tempSum += nums[right];
while (tempSum >= target && left <= right) {
ans = min(ans, right - left + 1);
tempSum -= nums[left++];
}
right++;
}
return ans == INT_MAX? 0: ans;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
left, right = 0, 0
temp_sum = 0
ans = None
while right < len(nums):
temp_sum += nums[right]
while temp_sum >= target and left <= right:
ans = right-left + 1 \
if ans is None \
else min(ans, right-left + 1)
temp_sum -= nums[left]
left += 1
right += 1
return 0 if ans is None else ans