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.code
時間 O(N) 空間 O(1)it
咱們用兩個指針維護一個窗口,保證這個窗口的內的和是小於目標數的。若是新來的數加上後,和大於目標,則比較下當前窗口長度和最短窗口長度,窗口左邊界右移。若是和仍小於目標數,則將窗口右邊界右移。注意這裏退出的條件,右邊界是小於等於長度,由於咱們窗口到了最右側時,還須要繼續左移左邊界來看有沒有更優的解法。另外,若是左邊界大於右邊界時,說明最短子串的長度已經小於等於1,咱們就不用再查找了。io
循環的判斷條件是right <= nums.length && left <= right
class
public class Solution { public int minSubArrayLen(int s, int[] nums) { if(nums.length == 0) return 0; int left = 0, right = 0, sum = 0, minLen = nums.length + 1; while(right <= nums.length && left <= right){ if(sum < s){ // 當右邊界等於長度時,咱們要多等一輪,等待左邊界左移,這時候不能加 if(right < nums.length){ sum += nums[right]; } right++; } else { // 當和大於等於目標時,檢查長度並左移邊界 minLen = Math.min(minLen, right - left); sum -= nums[left]; left++; } } return minLen <= nums.length ? minLen : 0; } }