题目:输入一个正数S,打印出所有和为S的连续正数序列(至少有两个数)。例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列15,46和7~8.
这个题目和上篇文章的解法类似,之前两个数字一个开头一个结尾,此次是两个起始位置相邻.
核心代码:
<pre><code>`
func findContinuousSequence(sum:Int) -> [[Int]]? {
if sum <= 0 {
return nil
}
var small:Int = 1
var big:Int = 2
let mid:Int = (1 + sum)/2
var allSequence:[[Int]] = []
var currentSum:Int = small + big // 至少两个数字,small最多到一半位置
while small < mid {
if currentSum == sum {// 相等保存
continuousSequence(small: small, big: big, data: &allSequence)
}
while currentSum > sum && small < mid { // 大于sum,增加small,先减后加
currentSum -= small
small += 1
if currentSum == sum {
continuousSequence(small: small, big: big, data: &allSequence)
}
}
big += 1// 小于sum,增加big
currentSum += big
}
return allSequence
}
func continuousSequence(small:Int,big:Int,data:inout [[Int]]) {
var temp:[Int] = []
for i in small...big {
temp.append(i)
}
data.append(temp)
}`</code></pre>
测试代码:
<pre><code>var sumSequenceArr:[[Int]]? = searchSum.findContinuousSequence(sum: 15) if sumSequenceArr != nil { print("FlyElephant-连续正数序列数组--\(sumSequenceArr!)") }
</code></pre>