LeetCode 1304. 和为零的N个唯一整数

    技术2024-07-27  16

    目录结构

    1.题目

    2.题解


    1.题目

    给你一个整数 n,请你返回 任意 一个由 n 个 各不相同 的整数组成的数组,并且这 n 个数相加和为 0 。

    示例:

    输入:n = 5 输出:[-7,-1,1,3,4] 解释:这些数组也是正确的 [-5,-1,1,2,3],[-3,-1,2,-2,4]。 输入:n = 3 输出:[-1,0,1] 输入:n = 1 输出:[0]

    提示:

    1 <= n <= 1000

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-n-unique-integers-sum-up-to-zero 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    2.题解

    将 n - 1 个自然数 1, 2, ..., n - 1 放入数组中,它们和为 sum。

    剩下的 1 个数,令其为 -sum,此时 n 个数的和为 0,且:

    当 n = 1 时,构造的答案中只有唯一的 1 个数 0;当 n > 1 时,我们构造的答案中包含 n - 1 个互不相同的自然数和 1 个负数。 public class Solution1304 { public int[] sumZero1(int n) { int[] result = new int[n]; int sum = 0; for (int i = 1; i < n; i++) { result[i] = i; sum -= i; } result[0] = sum; return result; } } 时间复杂度:空间复杂度:
    Processed: 0.009, SQL: 9