[刷题防痴呆] 0209 - 长度最小的子数组
2022-01-28 本文已影响0人
西出玉门东望长安
题目地址
https://leetcode.com/problems/minimum-size-subarray-sum/description/
题目描述
209. Minimum Size Subarray Sum
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.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
思路
- 滑动窗口.
- 用两根指针对数组进行一次遍历即可.
关键点
- 如果当前和小于s, 右指针右移, 扩大区间, 反之左指针右移, 缩小区间.
- 在这个过程中维持区间的和不小于s, 然后更新答案即可.
代码
- 语言支持:Java
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int sum = 0;
for (int left = 0, right = 0; right < nums.length; right++) {
sum += nums[right];
while (left < nums.length && sum >= target) {
res = Math.min(res, right - left + 1);
sum -= nums[left];
left++;
}
}
if (res == Integer.MAX_VALUE) {
return 0;
}
return res;
}
}