Topic: Enter a positive number s, and print out all consecutive positive numbers whose sum is s (containing at least two numbers).
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
Note: Two pointers are also used, but this time they are on the same side and move backward. If the sum of the numbers in the current two pointers is less than the target value, the back pointer moves to the right; if the sum is greater than the target value, the front pointer Move right; if the value is equal to the target value, it will be added to the saved list. The optimization is terminated early, when the previous pointer is greater than half the target value, it can be terminated.