Medium
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.
這道題看的答案,連暴力法也沒有自主想出來(lái)。一開始讓左右指針都為0, sum = nums[0], minLen = Integer.MAX_VALUE.當(dāng)sum >= s時(shí),說(shuō)明現(xiàn)在的subArray的和過大,不一定是最短的滿足sum >= s的子數(shù)組。此時(shí)就更新一下minLen, 然后刪掉現(xiàn)在的subArray的第一個(gè)元素,也就是最靠左的元素,讓left index遞增,去尋找是否有更短的subArray的可能; 如果sum < s, 則向右移動(dòng)right指針,sum += nums[right], 繼續(xù)進(jìn)行whiile循環(huán)。但是如果此時(shí)right已經(jīng)達(dá)到最右,則需要注意這個(gè)時(shí)候已經(jīng)不能再繼續(xù)增加sum。 檢查此時(shí)的minLen, 如果還是初始值,說(shuō)明整個(gè)過程中我們都沒有遇到sum >= s的情況,如果不是初始值了,說(shuō)明遇到過sum >= s的情況,而我們?cè)趧h掉left,右移left pointer的時(shí)候sum變小,變得sum < s了,這個(gè)時(shí)候我們直接返回記錄到的minLen就好了。
class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0){
return 0;
}
int l = 0;
int r = 0;
int sum = nums[0];
int minLen = Integer.MAX_VALUE;
while (r < nums.length){
if (sum >= s){
minLen = Math.min(minLen, r - l + 1);
sum -= nums[l];
l++;
} else {
if (r == nums.length - 1){
if (minLen == Integer.MAX_VALUE){
minLen = 0;
}
break;
}
r++;
sum += nums[r];
}
}
return minLen;
}
}