leetcode209 Minimum Size Subarray Sum

 1 """
 2 Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
 3 Example:
 4 Input: s = 7, nums = [2,3,1,2,4,3]
 5 Output: 2
 6 Explanation: the subarray [4,3] has the minimal length under the problem constraint.
 7 """
 8 """
 9 滑动窗口,与leetcode713类似
10 """
11 class Solution:
12     def minSubArrayLen(self, s: int, nums):
13         _sum = 0
14         res = len(nums) + 1
15         i = 0
16         for j in range(len(nums)):
17             _sum += nums[j]
18             while _sum >= s: #!!!
19                 res = min(res, j-i+1)
20                 _sum -= nums[i]
21                 i += 1
22         return res if res <= len(nums) else 0

 

上一篇:回转体零件厚度测量


下一篇:ROS2学习笔记之编写Python服务service和client节点篇