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. 暴力求解:依次遍歷每個元素,尋找以這個元素為起點的連續和大于s的最短長度,時間復雜度O(n2)。
  2. 用兩個指針,分別指向當前區間首尾,如果當前區間的和大于s,則更新min length。并且嘗試不斷右移指向首部的指針,直到當前區間的和小于s。最差情況是需要遍歷兩倍數組長度,時間復雜度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;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容