Skip to content

Commit 0bc6019

Browse files
author
Dinghao LI
committed
041
1 parent 63c9e81 commit 0bc6019

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#和为S的连续正数序列
2+
3+
解题思路
4+
5+
考虑用两个数start和end分别表示序列的最小值和最大值。首先把start初始化为1, end初始化为2。如果从start到end的序列的和大于s,我们可以从序列中去掉较小的值,也就是增大start的值。如果从start到end的序列的和小于s,我们可以增大big,让这个序列包含更多的数字。因为这个序列至少要有两个数字,我们一直增加start到(1+s)/2 为止。
6+
7+
以求和为9 的所有连续序列为例,我们先把start初始化为1, end初始化为2。此时介于start和end之间的序列是{1,2},序列的和为3,小于9,所以我们下一步要让序列包含更多的数字。我们把end增加1 变成3,此时序列为{ I, 2,坷。由于序列的和是6,仍然小于9,我们接下来再增加end变成4,介于start和end之间的序列也随之变成{ l, 2, 3, 4}。由于列的和10 大于9,我们要删去去序列中的一些数字, 于是我们增加start变成2,此时得到的序列是{2, 3, 4}, 序列的和E好是9。我们找到了第一个和为9 的连续序列,把它打印出来。接下来我们再增加big,重复前面的过程,可以找到第二个和为9 的连续序列{4,5}。
8+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func arraySum(target int) []int{
8+
if target < 3 { return []int{} }
9+
start, end := 1, 2
10+
sum := 3
11+
for end <= target/2+1 {
12+
if sum == target {
13+
break
14+
} else if sum < target {
15+
end++
16+
sum += end
17+
} else {
18+
sum -= start
19+
start++
20+
}
21+
}
22+
res := []int{}
23+
if sum == target {
24+
for i:=start; i<=end; i++{
25+
res = append(res, i)
26+
}
27+
}
28+
return res
29+
}
30+
31+
func main() {
32+
fmt.Println("5 : ", arraySum(5))
33+
fmt.Println("100 : ", arraySum(100))
34+
}
35+

0 commit comments

Comments
 (0)