leetcode_209 Minimum Size Subarray Sum

题目描述

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.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

思路分析

这个题不是很难,双指针遍历即可,尾指针顺序扫描数组,同时记录首尾指针之间的数组和,如果满足要求( ≥ s \geq s s),则进一步判断长度是否比已有的短。扫到一个满足要求的子数组后,我们开始向尾部移动头指针,并做长度更新,直到子数组的和不满足要求。
当尾指针遍历完成后,结束。
Python 代码如下

class Solution:
    def minSubArrayLen(self, s: int, nums: List[int]) -> int:
        ls = len(nums)
        tp1,tp2 =0,0
        val, result = 0, ls + 1
        while tp2 < ls:
            val += nums[tp2]
            while val >= s:
                result = min(result, tp2-tp1+1)
                val -= nums[tp1]
                tp1 += 1
            tp2 +=1
        return result if result <= ls else 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值