LeetCode Algorithm 剑指 Offer 57 - II. 和为s的连续正数序列

Posted Alex_996

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Algorithm 剑指 Offer 57 - II. 和为s的连续正数序列相关的知识,希望对你有一定的参考价值。

剑指 Offer 57 - II. 和为s的连续正数序列

Ideas

区间问题首先想到用双指针。

因为这题没有给定数组,其实相当于就是一个从1到target的数组,然后直接套双指针的模板就可以了。

双指针教程参考:https://www.yuque.com/huoxiangshouxiangwanghuo/ndi0dn/moq12q

Code

Python

from copy import deepcopy
from typing import List


class Solution:
    def findContinuousSequence(self, target: int) -> List[List[int]]:
        left, right = 1, 1
        ans, res, sums = [], [], 0
        while right < target:
            sums += right
            while sums > target:
                sums -= left
                res.pop(0)
                left += 1
            res.append(right)
            right += 1
            if sums == target:  # 如果找到一个符合条件的区间
                ans.append(deepcopy(res))
        return ans

以上是关于LeetCode Algorithm 剑指 Offer 57 - II. 和为s的连续正数序列的主要内容,如果未能解决你的问题,请参考以下文章