【Leetcode】面试题57 - II. 和为s的连续正数序列 Python

思路:

等差数列求和

代码: 

def findContinuousSequence(target: int):
    res = []
    # Solution 1 迭代
    for i in range(1, target // 2 + 1):
        length = (-2 * i + 1 + ((2 * i - 1) ** 2 + 8 * target) ** 0.5) / 2
        if length - round(length) == 0:
            res.append([item for item in range(i, i + round(length))])
    return res

    # Solution 2 循环
    # for i in range(1, target // 2 + 1):
    #     length = (-2 * i + 1 + ((2 * i - 1) ** 2 + 8 * target) ** 0.5) / 2
    #     if length - round(length) == 0:
    #         temp = []
    #         for j in range(i, i + round(length)):
    #             temp.append(j)
    #         res.append(temp)
    # return res

    # Solution 3 双迭代
    # res = []
    # for i in range(1, target // 2 + 1):
    #     length = (-2 * i + 1 + ((2 * i - 1) ** 2 + 8 * target) ** 0.5) / 2
    #     res.append([item for item in range(i, i + round(length)) if length - round(length) == 0])
    # return [result for result in res if result != []]


total = 9
print(findContinuousSequence(total))
发布了29 篇原创文章 · 获赞 2 · 访问量 1394

猜你喜欢

转载自blog.csdn.net/Lucky_Z1111/article/details/104706959