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.
题目大意:
给一个正整数数组,找出最短的连续子数组的长度,使得子数组的和大于给定和,如果不存这样的连续子数组,则返回0。
解法:
采用两个指针,遍历数组,一旦和比给定和要大时,记录长度并且调整指针,这种解法的时间复杂度是O(n)。
java:
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int start=0,end=0;
int tmpSum=0;
int res=Integer.MAX_VALUE;
while(end<nums.length){
tmpSum+=nums[end];
while(start<=end&&tmpSum>=s){
res=Math.min(res,end-start+1);
tmpSum=tmpSum-nums[start];
start++;
}
end++;
}
return res==Integer.MAX_VALUE?0:res;
}
}
leetcode [209]Minimum Size Subarray Sum
原文:https://www.cnblogs.com/xiaobaituyun/p/10773254.html