Python easy to understand solution with comments.


  • 0
    C
    # O(n) time
    # we scan from left to right, "total" tracks the 
    # sum of the subarray. If the sum is less than s,
    # right moves forward one step, else left moves forward
    # one step, left and right form a window.
    def minSubArrayLen(self, s, nums):
        total = left = right = 0
        res = len(nums) + 1
        while right < len(nums):
            total += nums[right]
            while total >= s:
                res = min(res, right-left+1)
                total -= nums[left]
                left += 1
            right += 1
        return res if res <= len(nums) else 0

  • 1
    C

    Actually the first while loop can be replaced by a for loop:

    def minSubArrayLen(self, s, nums):
        l = sum = 0
        res = len(nums)+1
        for i in xrange(len(nums)):
            sum += nums[i]
            while sum >= s:
                res = min(res, i-l+1)
                sum -= nums[l]
                l += 1
        return res if res <= len(nums) else 0

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.