268. Missing Number
題目網址:https://leetcode.cn/problems/missing-number/
題意:原本有一包含
[0, n]總共n + 1個數的 array, 今給一只有n個數的 arraynums, 找出缺失的數。

Solution 1:
想法:先將
nums排序, 然後用 loop 檢查第i個數是否在nums中
class Solution { |
- time:$O(n \cdot log(n))$ ➔ sorting
- space:$O(1)$ ➔ sorting 後 data 仍儲存在
nums中, 不需要額外空間
Solution 2:
想法:先計算
[0, n]這n + 1個數之和, 然後扣掉nums中 data 之和, 即可得到缺失的數
class Solution { |
- time:$O(n)$ ➔ 遍例
nums計算所有 data 之和 - space:$O(1)$ ➔ 只需常數空間
Solution 3:
想法:利用 XOR 中
a ^ a = 0且0 ^ a = a的特性(還有交換性)e.g.
[0, 1, 2, 3] ^ [0, 1, 3] = 2XOR:
0 ^ 0 = 0b ^ b = b0 ^ a = aa ^ b ^ b = a ^ (b ^ b) = a ^ 0 = a- 交換性:
b ^ a ^ b = a ^ (b ^ b) = a ^ 0 = a
class Solution { |
- time:$O(n)$ ➔ 遍歷
nums - space:$O(1)$ ➔ 只需常數空間
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論