题目:
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列?
思路:
连续正数序列为等差数列,和为cur =(low + high)*(high - low +1)/2,定义两个指针,low=1,high=2,当和>cur时low+=1,反之high+=1
代码:
# -*- coding:utf-8 -*-
class Solution:
def FindContinuousSequence(self, tsum):
# write code here
###定义两个指针
low = 1
high = 2
all_result = []
while low < high:
cur = (low + high)*(high - low +1)/2
if cur < tsum:
high += 1
elif cur == tsum:
all_result.append(list(range(low,high+1)))
low +=1
else:
low +=1
return all_result