Leetcode 209 Minimum Size Subarray Sum (双指针)

Leetcode 209

问题描述

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.

方法

** Solution Java **
** 1ms, beats 99.94% **
** 43MB, beats 5.71% **
class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int n = nums.length, res = Integer.MAX_VALUE, cur = 0;
        for (int i = 0, j = 0; j < n; ++j) {
            cur += nums[j];
            while (s <= cur) {
                res = Math.min(res, j - i + 1);
                cur -= nums[i++];
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}
** Solution Python3 **
** 72ms, beats 88.08% **
** 15.5MB, beats 7.69% **
class Solution:
    def minSubArrayLen(self, s: int, nums: List[int]) -> int:
        n, i = len(nums), 0
        res = n + 1
        for j in range(n) :
            s -= nums[j]
            while (s <= 0) :
                res = min(res, j - i + 1)
                s += nums[i]
                i += 1
        return res % (n + 1)
posted @ 2020-03-18 09:49  willwuss  阅读(83)  评论(0编辑  收藏  举报