-
Notifications
You must be signed in to change notification settings - Fork 5
/
5702.py
52 lines (42 loc) · 1.35 KB
/
5702.py
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
47
48
49
50
51
52
from typing import List
class Solution:
def findContinuousSequence(self, target: int) -> List[List[int]]:
# solution one: sliding window
i, j = 1, 1
sum = 0
res = []
while i <= target // 2:
if sum < target:
# j + 1
sum += j
j += 1
elif sum > target:
# i + 1
sum -= i
i += 1
else:
arr = list(range(i, j))
res.append(arr)
# i + 1
sum -= i
i += 1
return res
# solution two: formula
res = []
for y in range(1, target // 2 + 2): # range:[ )
x = (1/4 + y**2 + y - 2*target) ** (1/2) + 0.5
if type(x) != complex and x - int(x) == 0: # x can't be complex and x must be int
res.append(list(range(int(x), y + 1)))
return res
# solution three
i, res = 1, []
while i*(i+1)/2 < target:
if not (target - i*(i+1)/2) % (i+1):
x = int((target - i*(i+1)/2) // (i+1))
res.append(list(range(x, x+i+1)))
i += 1
# reverse
return res[::-1]
if __name__ == "__main__":
target = 9
print(Solution().findContinuousSequence(target))