209. Minimum Size Subarray Sum
給定一個由正整數組成的陣列 nums 和一個正整數 target,返回總和大於或等於 target 的最小子陣列長度。如果沒有這樣的子陣列,則返回 0。
範例:
輸入:target = 7, nums = [2,3,1,2,4,3]
輸出:2
解釋:子陣列 [4,3] 符合條件且長度最短。
Python
from typing import List
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n = len(nums)
min_length = float('inf')
left = 0
current_sum = 0
for right in range(n):
current_sum += nums[right]
while current_sum >= target:
min_length = min(min_length, right - left + 1)
current_sum -= nums[left]
left += 1
return min_length if min_length != float('inf') else 0
30.41MB, 196ms
C++
#include <vector>
#include <algorithm>
#include <limits.h>
using namespace std;
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int n = nums.size();
int min_length = INT_MAX;
int left = 0;
int current_sum = 0;
for (int right = 0; right < n; ++right) {
current_sum += nums[right];
while (current_sum >= target) {
min_length = min(min_length, right - left + 1);
current_sum -= nums[left];
++left;
}
}
return min_length == INT_MAX ? 0 : min_length;
}
};
30.88MB, 23ms
Javascript
/**
* @param {number} target
* @param {number[]} nums
* @return {number}
*/
var minSubArrayLen = function(target, nums) {
let n = nums.length;
let minLength = Infinity;
let left = 0;
let currentSum = 0;
for (let right = 0; right < n; right++) {
currentSum += nums[right];
while (currentSum >= target) {
minLength = Math.min(minLength, right - left + 1);
currentSum -= nums[left];
left++;
}
}
return minLength === Infinity ? 0 : minLength;
};
53.20MB, 47ms