zoukankan      html  css  js  c++  java
  • 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.

    For example, given the array [2,3,1,2,4,3] and s = 7,
    the subarray [4,3] has the minimal length under the problem constraint.

    click to show more practice.

    More practice:

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

    题意:获取最短子串的长度,使其总和大于等于给定的值s
     
     1     public int minSubArrayLen(int s, int[] nums) {
     2 //        定义两个指针left和i,分别记录子数组的左右的边界位置,每次i右移1位,就将结果累加到sum中。
     3 //        找出left到i范围内sum大于s时最小的长度(i-left+1),然后将left右移,同时在sum中去除nums[left]的值
     4         int res = Integer.MAX_VALUE, left = 0, sum = 0;
     5         for (int i = 0; i < nums.length; ++i) {
     6             sum += nums[i];
     7             while (left <= i && sum >= s) {
     8                 res = Math.min(res, i - left + 1);
     9                 sum -= nums[left++];
    10             }
    11         }
    12         return res == Integer.MAX_VALUE ? 0 : res;        
    13     }
  • 相关阅读:
    css定位
    Register Form
    自我介绍
    靠,用 mod_proxy_ajp 代替 mod_jk 不知简单多少倍
    Mac 切换 32 和 64
    JAVA面向对象(8)
    JAVA面向对象(7)
    JAVA面向对象(6)
    JAVA面向对象(5)
    JAVA面向对象(4)
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7677503.html
Copyright © 2011-2022 走看看