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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容