zoukankan      html  css  js  c++  java
  • leetcode 209. Minimum Size Subarray Sum 找出最小的和的长度 ---------- java

    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.

    给出一个数组,找出数组中和大于等于s的最小长度。

    1、计算sum,然后找出以每一位开头的和大于等于s的长度。

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            int len = nums.length;
            if (len == 0){
                return 0;
            }
            if (nums[0] >= s){
                return 1;
            }
            int i = 0, result = 0, sum = 0;
            for (; i < len; i++){
                sum += nums[i];
                if (sum >= s){
                    break;
                }
            }
            if (i == len && sum < s){
                return 0;
            }
            i++;
            result = i;
            sum -= nums[0];
            for (int j = 1; j < len; j++){
                while (i < len && sum < s){
                    sum += nums[i];
                    i++;
                }
                if (sum < s){
                    break;
                }
                result = Math.min(i - j, result);
                sum -= nums[j];
            }
            return result;
           
        }
    }
    

    2、还可以判断从0~len-1位,以每一位为结尾的最小的长度。

    public class Solution {
        public int minSubArrayLen(int s, int[] nums) {
            if (nums.length == 0){
                return 0;
            }
            int i = 0, j = 0, sum = 0, min = Integer.MAX_VALUE;
            
            while (j < nums.length){
                sum += nums[j++];
                
                while (sum >= s){
                    min = Math.min(min, j - i);
                    sum -= nums[i++];
                }
            }
            return min == Integer.MAX_VALUE ? 0 : min;
    
        }
    }
  • 相关阅读:
    wc
    1.11考试
    diff
    C++11新利器
    vimdiff
    [学习笔记]多项式
    rev
    [AH2017/HNOI2017]礼物
    tr
    bzoj2555: SubString
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6633322.html
Copyright © 2011-2022 走看看