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] = 2
XOR:
0 ^ 0 = 0
b ^ b = b
0 ^ a = a
a ^ 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!
評論