题目原址
https://leetcode.com/problems/minimum-size-subarray-sum/description/
题目描述
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: [2,3,1,2,4,3], s = 7
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
解题思路
该题是寻找给定数组中连续数组中的元素和>=s的最少元素个数。
这里有两种解法,一种是使用双层循环,当然时间耗费的多一些。
另一种是使用滑动窗口的方法。首先定义两个变量left
和right
,left
表示数组中左边的元素,right
表示数组中相对左边元素的右边元素,进入循环判断,如果right+1小于数组长度,并且和小于给定的s,则需要将当前元素加入到sum中,否则将最左边的元素从sum中取出来。这样就相当于一个滑动窗口一样。最后元素的个数为右边元素下标-左边元素下标
AC代码
解法一:
public int minSubArrayLen(int s, int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int ret = Integer.MAX_VALUE;
int sum = 0;
int count = 0;
for(int i = nums.length - 1; i >= 0; i--) {
sum = 0;
int j = i;
count = 0;
while(sum < s && j >= 0) {
sum += nums[j];
j--;
count++;
}
if(sum >= s)
ret = Math.min(ret, count);
}
if(ret == Integer.MAX_VALUE)
return 0;
return ret;
}
解法二:滑动窗口
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int left = 0, right = -1;
int ret = nums.length + 1;
int sum = 0;
while(left >= 0 && left < nums.length) {
if(right + 1 < nums.length && sum < s) {
right ++;
sum += nums[right];
}else {
sum -= nums[left];
left ++;
}
if(sum >= s)
ret = Math.min(ret, right - left + 1);
}
if(ret == nums.length + 1)
return 0;
return ret;
}
}