LeetCode209. 长度最小的子数组
一、题目描述
☆☆二、解法
方法1:滑动窗口. 时间复杂度 O(n) 、空间复杂度 O(1)
连续子数组 ---> 【滑动窗口】
class Solution { public int minSubArrayLen(int s, int[] nums) { if (nums == null || nums.length == 0) return 0; /** * 写法1 */ /* int l = 0, r = -1; // 定义[l...r]为滑动窗口,初始化为-1表示窗口不包含任何元素 int res = nums.length + 1; // 这个值是取不到的最大值 int tempSum = 0; while (l < nums.length) { if (tempSum >= s) { res = Math.min(res, r - l + 1); tempSum -= nums[l]; l ++; }else { // tempSum < s if (r < nums.length - 1) { // 注意此边界! r ++; tempSum += nums[r]; }else { break; } } } return res > nums.length ? 0 : res; */ /** * 写法2 * 扩张窗口:为了找到一个可行解,找到了就不再扩张 * 收缩窗口:在长度上优化该可行解,直到条件被破坏 * 寻找下一个可行解,然后再优化到不能优化…… */ int l = 0, r = 0; int res = nums.length + 1; int tempSum = 0; while (r < nums.length) { // 主旋律是扩张,找可行解 tempSum += nums[r]; while (tempSum >= s) { // 间歇性收缩,优化可行解,让窗口长度挑战最小纪录 res = Math.min(res, r - l + 1); tempSum -= nums[l]; l ++; } r ++; } return res > nums.length ? 0 : res; } }