Sword Finger Offer——Sequence of continuous positive numbers with S (implemented by JS)

Title description

Problem-solving ideas

  • Use two variables, left and right, to replace the left and right borders of the sliding window.
  • The condition of the core while loop is: as long as the left boundary is less than half of the target value, it will enter the loop, as long as it is not less than the end of the loop, it means that it has been found at this time.
  • Define the temp variable to store the sum of all elements in the sliding window.
  • When temp is less than the value of target, the right boundary is expanded by one to the right.
  • When temp is greater than target, one from the left to the right

Implementation code

var findContinuousSequence = function(target) {
    
    
    let left = 1;
    let right = 1;
    let arr = [];
    let temp = 0;
    // 下面的这个result数组是用来返回的
    let result = [];
    // 核心判断条件是当 left >= target/2 的时候 left + tight >= target
    while (left < (target/2)) {
    
    
        while (temp < target) {
    
    
            temp = temp + right;
            arr.push(right);
            right += 1;
        }
        while (temp > target) {
    
    
            temp = temp - left;
            arr.shift();
            left += 1;
        }
        if (target === temp) {
    
    
            temp = temp - left;
            left++;
            result.push([...arr]);
            arr.shift();
        }
    }
    return result;
};

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/115278463