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.

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(n log n).

解法思路

  • 從數(shù)組的起始處撐開一個(gè)滑動(dòng)窗口;
  • 以目標(biāo)值 s 和窗口的值 windowLength 的大小關(guān)系作為窗口拉長和縮短的依據(jù);
  • 在窗口拉長和縮短的過程中,維護(hù)窗口的值 windowSum 和長度 windowLength ;
  • 在每次窗口的長度發(fā)生變化后,檢查窗口的值 windowSum 是否 >= s 時(shí),并在滿足條件的情況下判斷是否出現(xiàn)了更短的窗口;

時(shí)間復(fù)雜度

  • O(N);

關(guān)鍵詞

滑動(dòng)窗口 數(shù)組 雙指針 二分查找

算法實(shí)現(xiàn)

  • lr 表示窗口的左右邊界;
  • 窗口完全滑出數(shù)組的情況是:l < nums.length
  • 注意窗口的右邊界 r 在滑動(dòng)的時(shí)候不能超過數(shù)組的右邊界;
package leetcode._209;

public class Solution {

    public int minSubArrayLen(int s, int[] nums) {
        int l = 0, r = -1;
        int windowSum = 0;
        int windowLength = nums.length + 1;

        while (l < nums.length) {
            if (r + 1 < nums.length && windowSum < s) {
                r++;
                windowSum += nums[r];
            } else {
                windowSum -= nums[l];
                l++;
            }

            if (windowSum >= s) {
                windowLength = Math.min(windowLength, (r - l + 1));
            }
        }

        if (windowLength == nums.length + 1) {
            return 0;
        }

        return windowLength;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, 1, 2, 4, 3};
        int windowLength = (new Solution()).minSubArrayLen(7, arr);
        System.out.println(windowLength);
    }

}

返回 LeetCode [Java] 目錄

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

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

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