Given an integer n, return any array containing n unique integers such that they add up to 0.
給定一個整數(shù)n耸袜,返回任何包含n個唯一整數(shù)的數(shù)組芜赌,以使它們的總和為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
Solution:
class Solution:
def sumZero(self, n: int) -> List[int]:
res = []
for i in range(n // 2):
res.append(i + 1)
res.append(-1 * (i + 1))
if n % 2 == 1:
res.append(0)
return res
For each time, we add a pair of positive and negative number. Since each number has to be unique, we need to use i +1 to avoid 0 pair.
每次我們添加一個數(shù)字正數(shù)和負(fù)數(shù)。由于每個數(shù)字都必須唯一,因此我們需要使用i +1來避免使用0對。