Leetcode第209题
题目:
给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [ n u m s l , n u m s l + 1 , . . . , n u m s r − 1 , n u m s r ] [nums_l, nums_{l+1}, ..., nums_{r-1}, nums_r] [numsl,numsl+1,...,numsr−1,numsr],并返回其长度。
如果不存在符合条件的子数组,返回 0 。
思路:
可以采用滑动窗口的思路来求解,滑动窗口是双指针的方法。
- 右指针用来寻找使得窗口值大于target的子序列,即滑动窗口的结束位置。移动右指针会增加序列的长度。当窗口的值小于target时,需要移动右指针;
- 左指针用来寻找有没有比当前已经符合条件的子序列更短的子序列。移动左指针会减小序列的长度。当窗口的值大于target时,需要移动左指针。
代码:
/*
* @lc app=leetcode.cn id=209 lang=java
*
* [209] 长度最小的子数组
*
* https://leetcode-cn.com/problems/minimum-size-subarray-sum/description/
*
* algorithms
* Medium (46.79%)
* Likes: 727
* Dislikes: 0
* Total Accepted: 173.2K
* Total Submissions: 370.2K
* Testcase Example: '7\n[2,3,1,2,4,3]'
*
* 给定一个含有 n 个正整数的数组和一个正整数 target 。
*
* 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr]
* ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
*
*
*
* 示例 1:
*
*
* 输入:target = 7, nums = [2,3,1,2,4,3]
* 输出:2
* 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
*
*
* 示例 2:
*
*
* 输入:target = 4, nums = [1,4,4]
* 输出:1
*
*
* 示例 3:
*
*
* 输入:target = 11, nums = [1,1,1,1,1,1,1,1]
* 输出:0
*
*
*
*
* 提示:
*
*
* 1
* 1
* 1
*
*
*
*
* 进阶:
*
*
* 如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。
*
*
*/
// @lc code=start
class Solution
{
public int minSubArrayLen(int target, int[] nums)
{
int left = 0;
int result = Integer.MAX_VALUE;
int sum = 0;
int subLength;// 记录每次符合条件的子序列的长度
for (int right = 0; right < nums.length; right++)
{
sum += nums[right];
// 滑动窗口的起始位置的调整
while (sum >= target)
{
subLength = right - left + 1;// 计算当前子序列的长度
result = Math.min(result, subLength);
// 调整滑动窗口的起始位置,寻找有没有比当前子序列更短的子序列
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
// @lc code=end