Leetcode 209. Minimum Size Subarray Sum

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.

思路:

  1. 暴力求解:依次遍歷每個元素,尋找以這個元素為起點的連續(xù)和大于s的最短長度,時間復雜度O(n2)。
  2. 用兩個指針,分別指向當前區(qū)間首尾,如果當前區(qū)間的和大于s,則更新min length。并且嘗試不斷右移指向首部的指針,直到當前區(qū)間的和小于s。最差情況是需要遍歷兩倍數(shù)組長度,時間復雜度O(n).
public int minSubArrayLen(int s, int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }

    int res = Integer.MAX_VALUE;
    int start = 0, end = 0, curSum = 0;
    while (end < nums.length) {
        curSum += nums[end];
        end++;
        while (curSum >= s) {
            res = Math.min(res, end - start);
            curSum -= nums[start];
            start++;
        }
    }

    return res == Integer.MAX_VALUE ? 0 : res;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容