一.问题描述
Given an integer n
, return any array containing n
unique integers such that they add up to 0.
Example 1:
Input: n = 5 Output: [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].
Example 2:
Input: n = 3 Output: [-1,0,1]
Example 3:
Input: n = 1 Output: [0]
Constraints:
1 <= n <= 1000
二.解题思路
题目是很简单的,最后的答案也不唯一,只要能满足和为0且元素各不相同的约束就可以了,主要介绍两种方法吧。
方法一:
每次添加两个元素进数组中,分别是[i,-i],这样子能保证添加的2个元素和为0。如果每次添加的2元组和为0,那么添加k个这样的二元组的数组的和也为0.
如果n是一个偶数,那么很完美,一直添加这样的二元组直到元素的个数为n。
扫描二维码关注公众号,回复:
8836924 查看本文章
如果n是一个奇数,需要多一步处理,n-1为偶数,添加到n-1个数,然后最后补一个0就好。
时间复杂度:O(N).
方法二:
前n-1个数顺序添加,最后一个数为负的前n-1个数的和。
实现方便的可以从1到n-1,因为这样子最后一个数直接是-(n-1)*n/2,可以直接公式算出来。
并且可以用*解包直接生成前n-1个数。
两种实现都给出来。
时间复杂度:O(N).
更多leetcode算法题解法: 专栏 leetcode算法从零到结束 或者 leetcode 解题目录 Python3 一步一步持续更新~
三.源码
方法一:from leetcode demo
class Solution:
def sumZero(self, n: int) -> List[int]:
a = []
for i in range(1,n//2+1):
a += [i,-i]
if n % 2 != 0 :
a += [0]
return a
方法二:
#version 1
class Solution:
def sumZero(self, n: int) -> List[int]:
return [i for i in range(1,n)]+[-n*(n-1)//2]
#version 2
class Solution:
def sumZero(self, n: int) -> List[int]:
return [*range(1,n)] +[-n*(n-1)//2]