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