Description
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
分析
题目的意思是:这道题给出n,求生成n个数,使得n个数的和为0. 我想了一个最笨的办法,记录前n-1个数的和,然后最后一个数为该和的复数,这样就能保证了,我在想这个怎么这么简单,看了一下答案,还有一种思路就是分奇数偶数,好像还没我这个简单哈哈哈。
代码
class Solution:
def sumZero(self, n: int) -> List[int]:
res=[]
t=0
for i in range(n-1):
t+=i
res.append(i)
res.append(-t)
return res