首页 > 其他 > 详细

LeetCode #1304. Find N Unique Integers Sum up to Zero

时间:2020-11-25 15:20:01      阅读:34      评论:0      收藏:0      [点我收藏+]

题目

1304. Find N Unique Integers Sum up to Zero


解题方法

首先计算正数和负数的个数,如果两个相加得到的结果比n小1,说明需要添加一个0,然后从1开始把正数放进数组,再从-1开始把负数放进数组,需要的话再加个零就行了。
时间复杂度:O(n)
空间复杂度:O(n)


代码

class Solution:
    def sumZero(self, n: int) -> List[int]:
        positive = n // 2
        negative = n // 2
        addzero = 0
        if positive + negative == n - 1:
            addzero = 1
        
        pos = [i for i in range(1, positive+1)]
        neg = [-i for i in range(1, negative+1)]
        
        if addzero:
            return pos + neg + [0]
        else:
            return pos + neg

LeetCode #1304. Find N Unique Integers Sum up to Zero

原文:https://www.cnblogs.com/RatsCommander/p/14035574.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!