代码随想录 -- 数组 -- 长度最小的子数组

第一次使用暴力解法超时了

class Solution(object):
    def minSubArrayLen(self, target, nums):
        """
        :type target: int
        :type nums: List[int]
        :rtype: int
        """
        i = j = k = 0
        for i in range(len(nums)):
            while sum(nums[i:j])<=target:
                if nums[i:j] == target:
                    if k>j-i+1:
                        k = j-i+1
                    break
                j = j+1
            i = i+1
        return k

题解使用滑动窗口

所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果

两个for循环,一个循环的索引指向子序列的起始位置,一个循环的索引指向子序列的终止位置。当只用一个for循环时,这个循环的索引一定表示滑动窗口的终止位置

因此,当窗口中的sum小于target时,for循环控制窗口的终止位置向后移,当sum大于target时,记录窗口中元素个数,窗口起始位置向后移。

class Solution(object):
    def minSubArrayLen(self, target, nums):
        """
        :type target: int
        :type nums: List[int]
        :rtype: int
        """
        i = res = sum = 0
        j = 0
        for j in range(len(nums)):
            sum = sum + nums[j]
            while sum>=target:
                if res == 0:
                    res = j-i+1
                if res>j-i+1:
                    res=j-i+1
                sum = sum - nums[i]
                i = i+1
            j = j + 1
        return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值