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.

    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).

    /*
    * 双指针sta和end,大循环是每次end++,比较两个指针间所有数的和和target的大小,大于的话进小循环,不断sta++,知道小于,每次都更新res
    * 两指针之间所有数的和的计算,一开始想到的是每次指针变动的时候都for循环进行相加,后来看了别人的方法,发现不用每次都重新加
    * 只要当end++后cur加上当前值,sta++前cur减去当前值就行,有点像回溯
    * 注意会有全部相加都小于的情况,最后要单独判断*/
    public int minSubArrayLen(int s, int[] nums) {
            //双指针
            int sta = 0;
            int end = 0;
            //length
            int res = nums.length + 1;
            //当前的和
            int cur = 0;
            //大循环
            while (end < nums.length)
            {
                cur += nums[end];
                //小循环
                while (cur >= s)
                {
                    res = Math.min(res,end - sta + 1);
                    cur -= nums[sta];
                    sta ++;
                }
                    end++;
            }
            //特殊情况判断
            if (res == nums.length + 1)
                return 0;
            return res;
        }
  • 相关阅读:
    2015/5/10站立会议(补发)
    2015/5/11站立会议(补发)
    2015/5/12站立会议(补发)
    5/13站立会议(补发)
    面向对象——抽象类和接口
    面向对象(三)——静态
    面向对象——三大特性(封装、继承、多态)
    ADO.NET
    面向对象 封装练习题
    面向对象 封装
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7411421.html
Copyright © 2011-2022 走看看