|
| 1 | +#================================================== |
| 2 | +#==> Title: 剑指 Offer 57 - II. 和为s的连续正数序列 |
| 3 | +#==> Author: Zhang zhen |
| 4 | +#==> Email: hustmatnoble.gmail.com |
| 5 | +#==> GitHub: https://github.com/MatNoble |
| 6 | +#==> Date: 2/21/2021 |
| 7 | +#================================================== |
| 8 | + |
| 9 | +""" |
| 10 | +https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/ |
| 11 | +""" |
| 12 | + |
| 13 | +from typing import List |
| 14 | +class Solution: |
| 15 | + def findContinuousSequence(self, target: int) -> List[List[int]]: |
| 16 | + # 滑动窗口 |
| 17 | + i = j = 1 |
| 18 | + sum_, res = 0, [] |
| 19 | + while i <= target // 2: # 左窗口不超过 target 的一半 |
| 20 | + while sum_ < target: # 扩大窗口, 右窗口右移 |
| 21 | + sum_ += j |
| 22 | + j += 1 |
| 23 | + while sum_ >= target: # 收缩窗口, 左窗口右移 |
| 24 | + if sum_ == target: # 添加结果 |
| 25 | + res.append([val for val in range(i, j)]) |
| 26 | + sum_ -= i |
| 27 | + i += 1 |
| 28 | + return res |
| 29 | + |
| 30 | +mat = Solution() |
| 31 | +target = 9 |
| 32 | +target = 15 |
| 33 | +mat.findContinuousSequence(target) |
0 commit comments