zoukankan      html  css  js  c++  java
  • [LeetCode] 209. Minimum Size Subarray Sum

    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.

    长度最小的子数组。题意是给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的连续子数组,返回 0。

    还是sliding window的思路做。给两个指针left和right,也用一个变量sum记录遍历到的数字们的加和。遍历的时候一开始也是只移动右指针,当sum >= S的时候,开始试图移动左指针。所谓的最短的子数组也就是左右指针的距离最短,所以每次当sum >= S的时候,需要记录right - left的值。注意有可能最后是找不到一个子数组满足其sum >= S的,如果是这种情况,需要输出0。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int minSubArrayLen(int s, int[] nums) {
     3         int res = Integer.MAX_VALUE;
     4         int left = 0;
     5         int right = 0;
     6         int sum = 0;
     7         while (right < nums.length) {
     8             sum += nums[right];
     9             right++;
    10             while (sum >= s) {
    11                 res = Math.min(res, right - left);
    12                 sum -= nums[left];
    13                 left++;
    14             }
    15         }
    16         return res == Integer.MAX_VALUE ? 0 : res;
    17     }
    18 }

    JavaScript实现

     1 /**
     2  * @param {number} s
     3  * @param {number[]} nums
     4  * @return {number}
     5  */
     6 var minSubArrayLen = function (s, nums) {
     7     let left = 0;
     8     let right = 0;
     9     let sum = 0;
    10     let res = Number.MAX_SAFE_INTEGER;
    11     while (right < nums.length) {
    12         sum += nums[right];
    13         right++;
    14         while (sum >= s) {
    15             res = Math.min(res, right - left);
    16             sum -= nums[left];
    17             left++;
    18         }
    19     }
    20     return res === Number.MAX_SAFE_INTEGER ? 0 : res;
    21 };

    sliding window相关题目

    LeetCode 题目总结

  • 相关阅读:
    git添加本地项目到git
    GitLab项目迁移到Gerrit
    flask一些资料
    openldap sshkey & 用户自定义属性
    openldap复制
    openldap主机访问控制(基于用户组)
    openldap主机访问控制(基于ip)
    openldap自定义schema
    openldap主机访问控制(基于hostname)
    openldap权限sudo
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12376937.html
Copyright © 2011-2022 走看看