LeetCode 题解工作台

和为零的 N 个不同整数

给你一个整数 n ,请你返回 任意 一个由 n 个 各不相同 的整数组成的数组,并且这 n 个数相加和为 0 。 示例 1: 输入: n = 5 输出: [-7,-1,1,3,4] 解释: 这些数组也是正确的 [-5,-1,1,2,3],[-3,-1,2,-2,4]。 示例 2: 输入: n = 3…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们可以从 开始,依次将正数和负数交替放入结果数组中,一共循环 次,如果 为奇数,则最后再将 放入结果数组中。 时间复杂度 ,其中 为给定的整数。忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

示例 2:

输入:n = 3
输出:[-1,0,1]

示例 3:

输入:n = 1
输出:[0]

 

提示:

  • 1 <= n <= 1000
lightbulb

解题思路

方法一:构造

我们可以从 11 开始,依次将正数和负数交替放入结果数组中,一共循环 n2\frac{n}{2} 次,如果 nn 为奇数,则最后再将 00 放入结果数组中。

时间复杂度 O(n)O(n),其中 nn 为给定的整数。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def sumZero(self, n: int) -> List[int]:
        ans = []
        for i in range(n >> 1):
            ans.append(i + 1)
            ans.append(-(i + 1))
        if n & 1:
            ans.append(0)
        return ans
speed

复杂度分析

指标
时间complexity is O(n) because each element is processed once. Space complexity is O(n) for storing the result array. No sorting or extra data structures are needed, so both are linear.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    You are expected to identify the symmetry pattern quickly.

  • question_mark

    Consider edge cases like n = 1 or very large n.

  • question_mark

    Look for an O(n) solution that avoids duplicates and ensures the sum is zero.

warning

常见陷阱

外企场景
  • error

    Forgetting to include zero when n is odd, breaking the sum requirement.

  • error

    Using random numbers without symmetry, leading to incorrect sums or duplicates.

  • error

    Attempting to sort or perform unnecessary checks, adding complexity without benefit.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return n unique integers summing to a target other than zero, using similar symmetry.

  • arrow_right_alt

    Construct the array with constraints such as all positive or all negative except one element.

  • arrow_right_alt

    Find n unique integers summing to zero, but return them sorted in ascending order.

help

常见问题

外企场景

和为零的 N 个不同整数题解:数组·数学 | LeetCode #1304 简单