题目:输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。
def find_continuous_seq(target):
if target<3:
return -1
begin,end = 1,2
res = []
mid = target/2
s = begin + end
while begin<=mid:
if s==target:
temp = []
i = begin
while i<=end:
temp.append(i)
i+=1
res.append(temp)
end += 1
s += end
elif s<target:
end+=1
s+=end
elif s>target:
s-=begin
begin+=1
return res
注:也是使用两个指针,只是这次在同一侧,向后侧移动,如果当前两个指针之内的数的和小于目标值,则后面指针右移;如果和大于目标值,则前面指针右移;如果和与目标值相等则加入保存的列表。优化提前终止为,前面指针大于目标值的一半时即可终止。