1. 题目
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
进阶:
如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n))
2. 题解
# 209
from typing import List
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
if nums is None or len(nums) == 0:
return 0
res = len(nums) + 1
total = 0
i = 0
j = 0
while j < len(nums):
total = total + nums[j]
j = j + 1
while total >= target:
res = min(res, j - i)
total = total - nums[i]
i = i + 1
if res == len(nums) + 1:
return 0
else:
return
import math
from typing import List
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
ans = math.inf
if len(nums) < 1:
return 0
n = len(nums)
i, j = 0, 0
total = 0
while j < n:
total += nums[j]
j += 1
while total >= target:
ans = min(ans, j - i)
total -= nums[i]
i += 1
if ans == math.inf:
return 0
else:
return ans
if __name__ == "__main__":
s = Solution()
nums = [2,3,1,2,4,3]
a = s.minSubArrayLen(7, nums)
print(a)