Skip to content

求长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。

leetcode 209 题,知识点: 双指针数组。

js
function minSubArrayLen(s, nums) {
  // 初始时,把长度设置为一个最大不可达的值
  let minLength = nums.length + 1;

  // 定义的 sum 区间为 [left, right] 上
  let left = 0;
  let right = -1;
  let sum = 0;
  while (left < nums.length) {
    if (sum < s && right + 1 < nums.length) {
      right += 1;
      sum += nums[right];
    } else {
      sum -= nums[left];
      left += 1;
    }
    if (sum >=s ) {
      minLength = Math.min(minLength, right - left + 1);
    }
  }
  return minLength === nums.length + 1 ? 0 : minLength;
}

// 时间复杂度为O(n)
// 空间复杂度为O(1)
js
const s = 7;
const nums = [2,3,1,2,4,3];

minSubArrayLen(s, nums);
// 2
// 子数组 [4,3] 是该条件下的长度最小的子数组。