[LintCode 406] Minimum Size Subarray Sum(Python)

题目描述

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn’t one, return -1 instead.
样例
Given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.

思路

前向双指针。快针定位到大于等于目标值子序列的最后一个元素,慢针再逼近到刚好小于目标值子序列的第一个元素。

代码

class Solution:
    """
    @param: nums: an array of integers
    @param: s: An integer
    @return: an integer representing the minimum size of subarray
    """
    def minimumSize(self, nums, s):
        # write your code here
        if nums is None or s <= 0:
            return -1
        n = len(nums)
        if n == 0: return -1
        l = r = t = 0
        res = n + 1
        while r < n:
            while r < n and t < s:
                t += nums[r]
                r += 1
            if t < s: break
            while l < r and t >= s:
                t -= nums[l]
                l += 1
            res = min(res, r - l + 1)
        if res == n + 1:
            return -1
        return res

复杂度分析

时间复杂度 O(n) ,空间复杂度 O(1)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值