程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> leetcode 209 : Minimum Size Subarray Sum

leetcode 209 : Minimum Size Subarray Sum

編輯:關於C++

Minimum Size Subarray Sum

Total Accepted: 1954 Total Submissions: 8526

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.

[思路]

兩個指針, start end, end向後走,直到 sum 大於 s. 然後start向後, 直到sum 小於s. 同時更新 min值.

 

 

public class Solution {
    //1,1,4
    public int minSubArrayLen(int s, int[] nums) {
        //init check
        int start = 0;
        int end = 0;
        
        int sum = 0;
        int min = Integer.MAX_VALUE;
        
        while(start=s && start<=end) {
                min = Math.min(min, end-start);
                sum -= nums[start++];
            }
        }
        return min==Integer.MAX_VALUE ? 0 : min;
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved