silver-hands / sss

0 stars 0 forks source link

【Q067】面试题57 - II. 和为s的连续正数序列 #67

Open fly0o0 opened 4 years ago

fly0o0 commented 4 years ago

面试题57 - II. 和为s的连续正数序列

fly0o0 commented 4 years ago

/**
 * @param {number} target
 * @return {number[][]}
 */
var findContinuousSequence = function(target) {
  let left = 1; // 滑动窗口的左边界
  let right = 1; // 滑动窗口的右边界
  let sum = 0; // 滑动窗口中数字的和

  const ret = []

  while (left <= target / 2) {

    if (sum < target) {
      // 右边界向右移动
      sum += right
      right++
    } else if (sum > target) {
      // 左边界向右移动
      sum -= left
      left++
    } else {
      // 记录结果
      let temp = []
      for (let c = left; c < right; c++) {
        temp.push(c)
      }
      ret.push(temp)
      sum -= left
      left++
    }
  }

  return ret
};