LeetCode 1304. Find N Unique Integers Sum up to Zero 查找N個唯一整數(shù)總和為零 (Easy)

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對。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容