zoukankan      html  css  js  c++  java
  • Minimum Size Subarray Sum

    Minimum Size Subarray Sum

    问题:

    Given an array of n positive integers and a positive integer s, find the minimal length of a 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.

    思路:

      双指针

    我的代码:

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            if(nums==null || nums.length==0)    return 0;
            int minLen = Integer.MAX_VALUE;
            int len = nums.length;
            int tmpSum = 0;
            
            for(int i=0,j=0; j<len; j++)
            {
                tmpSum += nums[j];
                if(tmpSum >= s)
                {
                    while(i <= j)
                    {
                        tmpSum -= nums[i];
                        if(tmpSum < s) 
                        {
                            tmpSum += nums[i];
                            break;    
                        }
                        else i++;
                    }
                    minLen = Math.min(minLen, j-i+1);
                }
            }
            
            return minLen==Integer.MAX_VALUE ? 0 : minLen;
        }
    }
    View Code

    学习之处:

    • 双指针的用处在于,后面的指针用于确定下界,前面的指针用于确定上界,然后前面的指针一直再向后指针靠近,尽量压缩之间的距离,也就是要求得的距离
    • 明明规划,i 变成start j变成end 更好一点
    • 改掉自己的坏习惯,稳住心态,不焦虑
  • 相关阅读:
    生产宕机dunp配置
    虚拟机下载地址
    处理soapUI特殊返回报文 【原】
    SpringMVC 手动控制事务提交 【转】
    码云URL
    Java IO流操作汇总: inputStream 和 outputStream【转】
    springMVC下载中文文件名乱码【转】
    js
    js
    js
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4511234.html
Copyright © 2011-2022 走看看