题目描述:

输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

示例 1:

输入:target = 9
输出:[[2,3,4],[4,5]]
示例 2:

输入:target = 15
输出:[[1,2,3,4,5],[4,5,6],[7,8]]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof

知识点:

  • 双指针,搜索

解题思路:

  • 这道题给我们一个目标值,让我们求某一连续正数序列的和为目标值
  • 假设目标值为9,那么可以取到的正数序列为2,3,4与4,5
  • 这道题我们可以用一个滑动窗口来解决,我们让窗口在[1~目标值]之间滑动,我们需要实时更新滑动窗口中的数据,如果滑动窗口中的数值大于目标值我们需要让滑动窗口的总值减去left,并且left++,相反我们需要让right++,滑动窗口的总值加上right
  • 最后特殊处理的是如果滑动窗口的总值等于目标值我们首先需要让right++,再进行计算,如果让left++可能会遗漏掉某些数

解题代码:

  1. function FindContinuousSequence(sum)
  2. {
  3. // write code here
  4. const res = [];
  5. function add (start,end){
  6. let arr = [];
  7. for(let i = start;i<=end;i++) {
  8. arr.push(i);
  9. }
  10. return arr;
  11. }
  12. let left = 1;
  13. let right = 2;
  14. let tempSum = left + right;
  15. while(left < right && right <= sum){
  16. if(tempSum === sum){
  17. res.push(add(left,right));
  18. right++
  19. tempSum += right;
  20. }else if(tempSum > sum){
  21. tempSum -= left;
  22. left++;
  23. }else if(tempSum < sum){
  24. right++;
  25. tempSum += right;
  26. }
  27. }
  28. return res;
  29. }