1. 程式人生 > >【LeetCode】209. Minimum Size Subarray Sum 解題報告(Python)

【LeetCode】209. Minimum Size Subarray Sum 解題報告(Python)

題目描述:

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.

Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

題目大意

找出一個數組中最短連續的子陣列,這個子陣列的和要>=s.

解題方法

碰巧今天在《挑戰程式設計競賽》一書中看到這個題,解法稱之為蟲取法,其實就是雙指標。其實看到讓連續子陣列滿足一定條件的很多都用了雙指標,比如713. Subarray Product Less Than K

因為這個題需要求最小值,所以結果初始化為inf,每次移動一下右指標,當和滿足條件的時候,更新結果,並移動左指標,同時記得把和刪去左邊的數字。

時間複雜度是O(N),空間複雜度是O(1)。

class Solution:
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        N = len(nums)
        l, r = 0, 0
        csum = 0
        res = float('inf')
        while r < N:
            csum +=
nums[r] while csum >= s: res = min(res, r - l + 1) csum -= nums[l] l += 1 r += 1 return res if res != float('inf') else 0

參考資料:

日期

2018 年 10 月 15 日 —— 美好的週一怎麼會出現霧霾呢?