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

    Question

    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.

    Solution 1 -- Two Pointers

    Following the thought of slide window, we apply two pointers here to solve the problem, one for left and one for right.

    If current sum >= target, left++;

    If current sum < target, right--;

    Remember to check right index before getting nums[right], and sum value is nums[0] at beginning.

    Time complexity O(n).

     1 public class Solution {
     2     public int minSubArrayLen(int s, int[] nums) {
     3         if (nums == null || nums.length == 0)
     4             return 0;
     5         int length = nums.length, left = 0, right = 0, result = length, sum = nums[0];
     6         while (right < length) {
     7             if (left == right) {
     8                 if (nums[left] >= s) {
     9                     return 1;
    10                 } else {
    11                     right++;
    12                     if (right < length)
    13                         sum += nums[right];
    14                     else
    15                         break;
    16                 }
    17             } else {
    18                 if (sum < s) {
    19                     right++;
    20                     if (right < length)
    21                         sum += nums[right];
    22                     else
    23                         break;
    24                 } else {
    25                     result = Math.min(result, right - left + 1);
    26                     sum -= nums[left];
    27                     left++;
    28                 }
    29             }
    30         }
    31         if (left == 0 && sum < s)
    32             result = 0;
    33         return result;
    34     }
    35 }
  • 相关阅读:
    项目工程化之git提交规范以及 CHANGELOG生成
    移动端 弹窗-内容可滚动,背景不动
    项目readme文件目录生成工具 treer
    css animation动画
    【网络】从套接字到Web服务器
    【网络】图解HTTP-1
    【MySQL】搞懂ACID原则和事务隔离级别
    【MySQL】备份与恢复
    【MySQL】索引
    【Redis】主从复制原理
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4806040.html
Copyright © 2011-2022 走看看