forked from Jack-Lee-Hiter/AlgorithmsByPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path和为s的连续整数序列.py
More file actions
46 lines (45 loc) · 1.37 KB
/
Copy path和为s的连续整数序列.py
File metadata and controls
46 lines (45 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'''
找出所有和为S的连续正数序列
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
'''
class Solution:
def FindContinuousSequence(self, tsum):
if tsum < 3:
return []
small = 1
big = 2
middle = (tsum + 1) // 2
curSum = small + big
output = []
while small < middle:
if curSum == tsum:
output.append(list(range(small, big+1)))
while curSum > tsum and small < middle:
curSum -= small
small += 1
if curSum == tsum:
output.append(list(range(small, big+1)))
big += 1
curSum += big
return output
def FindContinuousSequence2(self, tsum):
if tsum < 3:
return []
small, big = 1, 2
middle = (tsum + 1) >> 1
curSum = small + big
output = []
while small < middle:
if curSum == tsum:
output.append(list(range(small, big + 1)))
big += 1
curSum += big
elif curSum > tsum:
curSum -= small
small += 1
else:
big += 1
curSum += big
return output
s = Solution()
print(s.FindContinuousSequence2(15))