zoukankan      html  css  js  c++  java
  • 【Leetcode】209. Minimum Size Subarray Sum

    Question:

    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.

    Tips:

    给定一个长度为n的正整数数组,以及一个正整数s。找到长度最小的连续子数组,使他们的和大于等于s,并返回子数组的长度。如果不存在这样的子数组,就返回0.

    思路:

    设置两个变量,slow记录子数组的第一个数字位置,fast记录子数组当前要加到sum的数字位置。

    fast从0位置开始向后移动,每次都加入到sum中sum+=nums[fast++];

    当sum>=s时,最终结果ans就取原来的ans与fast-slow+1之间的最小值。在对sum进行减操作,减掉nums[slow],并继续判断sum是否仍然大于等于s。如果扔>=,slow向前移动,继续减nums[slow],

    否则再继续在sum上加nums[fast]。

    代码:

    public int minSubArrayLen(int s, int[] nums) {
            if(nums==null || nums.length<=0) return 0;
            int len=nums.length;
            int ans=Integer.MAX_VALUE;
            int slow=0,fast=0;
            int sum=0;
            while(fast<len){
                sum+=nums[fast++];
                while(sum>=s){
                    //前面sum与nums[fast++]相加,fast也自加了1,所以比较min与fast-slow即可
                    ans=Math.min(fast-slow,ans);
                    sum-=nums[slow++];
                    if(sum==0)return 1;//代表刚减掉的nums[slow]=s
                }
            }
            return ans==Integer.MAX_VALUE?0:ans;
        }
  • 相关阅读:
    STL源代码剖析(二)
    局域网部署docker--从无到有创建自己的docker私有仓库
    Leetcode Add two numbers
    GDIPlus绘制桌面歌词
    Android中apk动态载入技术研究(2)android插件化及实现
    jq 地区(省市县区)联动菜单
    System.Diagnostics.Process.Start的妙用
    aaaa
    RESTful Web 服务:教程
    芒果TV 视频真实的地址获取
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8549726.html
Copyright © 2011-2022 走看看