https://leetcode-cn.com/problems/minimum-size-subarray-sum/submissions/
@代码随想录
1.暴力解法
class Solution {
public static int minSubArrayLen(int target, int[] nums) {
//暴力解法:从每一个数开始直到和》target为止,并记录下这个数
//求数组长度 num.length
//求字符串长度 s.length()
int length = nums.length;
int[] result = new int[length];
for(int i = 0; i < length ; i++){
int sum = 0;
for(int j = i; j < length; j++){
sum += nums[j];
if(sum >= target){
result[i] = j - i + 1;
break;
}
}
}
//单独判断最后一个数字
if(nums[length - 1] < target){
result[length - 1] = length + 1;
}
int min = result[length - 1];
for(int k = 0; k < length; k++){
//System.out.print(result[k] + " ");
//System.out.print(" ----- ");
if(result[k] == 0){result[k] = length + 1;}
//System.out.print(result[k] + " ");
if(result[k] < min){
min = result[k];
}
}
if(min == length + 1){return 0;}
return min;
}
//此方法优化:不需要新建立数组再一个个比较,直接定最小值然后不断更新最小值,如果最小值一直是0,那么就返回0
}
注意:
求数组的长度 num.length
求字符串的长度 s.length()
滑动窗口
在本题中实现滑动窗口,主要确定如下三点:
- 窗口内是什么?
- 如何移动窗口的起始位置?
- 如何移动窗口的结束位置?
窗口就是 满足其和 ≥ s 的长度最小的 连续子数组。
窗口的起始位置如何移动:如果当前窗口的值大于s了,窗口就要向前移动了(也就是该缩小了)。
窗口的结束位置如何移动:窗口的结束位置就是遍历数组的指针,窗口的起始位置设置为数组的起始位置就可以了。
解题的关键在于 窗口的起始位置如何移动。
class Solution {
public static int minSubArrayLen(int target, int[] nums) {
//result的初始值为一个不可能的值
int result = nums.length + 1;
int left = 0;
int length = nums.length;
int sum = 0;
for(int right = 0;right < length; right++){
//向右滑动
sum += nums[right];
while(sum >= target){
result = Math.min(result, right - left + 1);
sum -= nums[left++];
//向左滑动
}
}
return result == nums.length + 1 ? 0 : result;
}
}