LeetCode 1304. Find N Unique Integers Sum up to Zero 查找N个唯一整数总和为零 (Easy)

Given an integer n, return any array containing n unique integers such that they add up to 0.
给定一个整数n,返回任何包含n个唯一整数的数组,以使它们的总和为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.
每次我们添加一个数字正数和负数。由于每个数字都必须唯一,因此我们需要使用i +1来避免使用0对。

你可能感兴趣的:(LeetCode 1304. Find N Unique Integers Sum up to Zero 查找N个唯一整数总和为零 (Easy))