[Title] algorithm and continuous positive number sequence s (Go solving)

topic

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

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

 
示例 1:

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

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

限制:

1 <= target <= 10^5

题目来源:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/

Disintegration ideas:
establishing two pointers l, r are eligible sequence start position and end position, according to the summation formula: ( a + b ) ( b a + 1 ) 2 {(a+b) * (b - a + 1)} \over {2} = Sum, for [l, r] Analyzing the results of the summation interval

  1. The meaning of the questions, the initial state is l = 1, r = 2 (sequence of at least two numbers, and a continuous sequence of positive integers)
  2. When [l, r] is equal to the interval and the target value, to find an eligible show sequence, the new interval value is the result of a sequence, and the right one will change the starting position,
  3. When [l, R & lt] is greater than the time interval and the target value, and the value indicates that the interval is too large, i.e., the current position as a starting position without qualifying sequence, l is the right one, continue traversing
  4. When [l, r] is less than the time interval and the target value, and the value indicates that the interval is too small, an R & lt right, continue traversing
  5. Repeat steps 2-4 until l> = r, i.e. [l, r] and subsequent sections has at least two sequence does not meet the condition number (r - l + 1)> = 2 condition, the end of traversal
  6. Return result res
  • In addition, because:
    ( a + b ) ( b a + 1 ) 2 {(a+b) * (b - a + 1)} \over {2} = s u m sum
    =
    ( a + b ) ( b a + 1 ) = s u m 2 {(a+b) * (b - a + 1)} = sum * 2
    Therefore, the determination can be performed traversal target * 2, which allows to reduce each traverse summation formula summing division operations, but also to avoid Results / 2 may be brought to a non-integer result and each cast int type of operation, improve the efficiency of certain.

go codes

//双指针法
func findContinuousSequence(target int) [][]int {
    if target < 3 {
        return [][]int{}
    }

    var res [][]int
    l := 1
    r := 2
    target = target << 1 //这里用位移预算代替*号运算,左移1位,将target * 2
    for l < r {
        sum := (l + r) * (r - l + 1) //减少了每次求和除法运算,也避免了/2带来的结果可能为非整数而每次将结果强制转换为int型的操作
        if sum == target {
            subRes := make([]int, r - l + 1)
            k := 0
            for j := l; j <= r; j++ {
                subRes[k] = j
                k++
            }
            res = append(res, subRes)
            l++
        } else if sum < target {
            r++
        } else {
            l++
        }
    }
    return res
}
Published 18 original articles · won praise 8 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_20408397/article/details/104692989