leetcode-面试题57

输入一个正整数 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

双指针

package main

import "fmt"

func findContinuousSequence(target int) [][]int {
    left := 1
    right := 1
    sum := 0
    res := make([][]int, 0)

    for left <= target / 2 {
        if sum < target {
            sum += right
            right++
        } else if sum > target {
            sum -= left
            left++
        } else {
            temp := make([]int, 0)
            //println(right-left)
            for i := left; i < right; i++ {
                temp = append(temp, i)
            }
            res = append(res, temp)
            sum -= left
            left++
        }
    }
    return res
}
func main() {
    res := findContinuousSequence(9)
    fmt.Println(res)
}

end

猜你喜欢

转载自www.cnblogs.com/CherryTab/p/12431185.html