• LeetCode 209 Minimum Size Subarray Sum 最小子数组和问题


    Given an array of n positive integers and a positive integer s, find the minimal length of a contiguoussubarray of which the sum ≥ s. If there isn't one, return 0 instead.

    Example: 

    Input: s = 7, nums = [2,3,1,2,4,3]
    Output: 2
    Explanation: the subarray [4,3] has the minimal length under the problem constraint.
    Follow up:
    If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(nlog n). 
     
    思路:使用滑动窗口,窗口右侧先向右扩张,使用一个变量sum来记录窗口中数字的总和,当sum大于s的时候,窗口左侧右移来缩小窗口并将sum减去nums[left]。重复此操作直到right到达数组的末尾,而left到达临界值。
     
     
     1 public class Minimum_Size_Subarray_Sum {
     2     public static int minSubArrayLen(int s, int[] nums) {
     3         if(null==nums||nums.length==0){
     4             return 0;
     5         }
     6         
     7         int left = 0;
     8         int minLeft = 0;
     9         int minLen = nums.length;
    10         int sum = 0;
    11         int maxSum = Integer.MIN_VALUE;
    12         
    13         for(int right=0;right<nums.length;right++){
    14             if(sum<s){
    15                 sum += nums[right];
    16                 if(sum>maxSum){
    17                     maxSum = sum;
    18                 }
    19             }
    20             
    21             while(sum>=s){
    22                 if(right-left+1<minLen){
    23                     minLeft = left;
    24                     minLen = right - left + 1;
    25                 }
    26                 
    27                 sum -= nums[left];
    28                 left++;
    29             }
    30         }
    31         
    32         if(maxSum<s){
    33             return 0;
    34         }
    35         
    36         return minLen;
    37     }
    38     
    39     public static void main(String[] args) {
    40         int[] nums = {1,1,1,1,1,1};
    41         System.out.println(minSubArrayLen(6, nums));
    42         
    43     }
    44 }

    类似题目:

       窗口最小子串问题  https://www.cnblogs.com/blzm742624643/p/10357757.html

  • 相关阅读:
    C# 特性学习笔记
    Nhibernate学习的第二天
    Nhibernate学习的第一天
    SQL循环添加表中的字段
    加班
    bat文件重启SQL服务和IIS服务
    判断是不是手机访问的网站
    解决Ueditor 不兼容IE7 和IE8
    实现链表的初始化,按值查找,插入,删除
    判断任一二叉树,是否为满二叉树.(输出二叉树,节点总数,二叉树深度)
  • 原文地址:https://www.cnblogs.com/blzm742624643/p/10359029.html
Copyright © 2020-2023  润新知