↓快轉到主要內容
  1. LeetCode/

LeetCode 1304: Find N Unique Integers Sum up to Zero

·1 分鐘· ·
LeetCode Easy Math Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-07-21

  • 提交紀錄:Wrong Answer ×2 → Accepted

解題思路
#

成對放 i 和 -i(i = 1..n/2),每一對和是 0,而且都不重複。n 是奇數時再放一個 0。

我的嘗試
#

  1. 第一版用 range(-n//2, n//2 + 1),偶數時多了一個數(包含 0)。例如 n = 2:回傳 [-1, 0, 1],三個數。
  2. 第二版偶數時把上界少 1,變成 [-1, 0],和不是 0。
  3. 改成先產生 -n//2..n//2,偶數時把中間的 0 拿掉,就 AC 了。

正確解法
#

class Solution:
    def sumZero(self, n: int) -> List[int]:
        res = []
        for i in range(1, n // 2 + 1):
            res += [i, -i]                         # 兩兩抵銷
        if n % 2:
            res.append(0)
        return res

複雜度
#

時間 O(n),空間 O(n)(輸出)。

要特別避免的錯誤
#

  • 偶數個時不能有 0(不然就多一個數,或要拿掉別的數)。

面試口說整理
#

我成對放 i 和 -i,每一對的和是 0,放 n / 2 對;n 是奇數時再補一個 0。時間 O(n)。

相關文章

LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 989: Add to Array-Form of Integer
·1 分鐘
LeetCode Easy Array Math
LeetCode 989 解題筆記:把 k 當成進位,從陣列最後一位往前加,k 還沒用完就繼續往前補位
LeetCode 908: Smallest Range I
·1 分鐘
LeetCode Easy Array Math
LeetCode 908 解題筆記:最大值往下調 k、最小值往上調 k,答案是 max(0, max - min - 2k)
LeetCode 914: X of a Kind in a Deck of Cards
·1 分鐘
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 解題筆記:每種卡片的張數都要能被同一個 X >= 2 整除,也就是所有張數的 GCD >= 2
LeetCode 892: Surface Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 解題筆記:每疊 v 個方塊有 4v + 2 個面,再扣掉跟上方和左方相鄰的疊重疊的 2 × min 面
LeetCode 883: Projection Area of 3D Shapes
·1 分鐘
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 解題筆記:俯視是非 0 的格子數,正視和側視分別是每一列、每一欄的最大值總和