zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    js 实现自增长
    常用的js脚本验证
    Jquery 收集
    Jquery 常用操作搜集
    Jquery 点击绑定行 弹出详细页面
    Jquery 了解
    Html 标尺
    Editor Guidelines
    程序员需要做到
    jS 回车事件
  • 原文地址:https://www.cnblogs.com/willwuss/p/12515531.html
Copyright © 2011-2022 走看看