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

LeetCode 268: Missing Number

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

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

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

解題思路
#

0..n 總共 n + 1 個數,陣列少了一個。完整的總和是 n(n + 1) / 2,減掉陣列的總和就是缺的那個。也可以用 XOR:0..n 和陣列的每個數全部 XOR,成對的抵銷,剩下的就是缺的。

我的嘗試
#

第一次就 AC 了。11 月重寫時一版排序後只檢查相鄰兩個數差距大於 1 的地方,缺的是 0 時找不到,例如 [1]:答案 0,回傳 1。

正確解法
#

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        return n * (n + 1) // 2 - sum(nums)

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 缺的可能是 0 或 n,排序後只看相鄰差距會漏掉這兩種。

面試口說整理
#

0 到 n 的總和是 n(n+1)/2,減掉陣列的總和就是缺的數字。時間 O(n)、空間 O(1)。

相關文章

LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值
LeetCode 367: Valid Perfect Square
·1 分鐘
LeetCode Easy Math Binary-Search
LeetCode 367 解題筆記:在 [1, num] 上二分找 mid² == num,不用 sqrt
LeetCode 202: Happy Number
·1 分鐘
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 解題筆記:一直取位數平方和,會走到 1 或進入環;用集合記看過的數,或用快慢指針判圈
LeetCode 217: Contains Duplicate
·1 分鐘
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 解題筆記:轉成 set 後長度變短就代表有重複
LeetCode 219: Contains Duplicate II
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 解題筆記:雜湊表記錄每個值最後一次出現的位置,只需要跟最近的那次比距離