題目#
leetcode 268 - Missing Number (題目說明請點連結)
題目簡述#
找出一個包含從 0 到 n 的 n 個不同數字的陣列中缺失的那個數字。
範例#
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3,缺失的數字是 2,因為它不在 [0,1,3] 中。Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2,缺失的數字是 2,因為它不在 [0,1] 中。Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9,缺失的數字是 8,因為它不在 [0,1,2,3,4,5,6,7,9] 中。解題思路#
這題要求我們找出一個包含從 0 到 n 的 n 個不同數字的陣列中缺失的那個數字。我們可以使用數學公式來計算出完整的總和,然後減去陣列中所有數字的總和,得到缺失的數字。
解法#
數學公式法(Mathematical Formula Approach)
- 計算完整的總和
total = n * (n + 1) / 2 - 遍歷陣列中的每個數字,從
total中減去該數字 - 最後
total的值即為缺失的數字
步驟#
- 初始化:
- 計算完整的總和
total = n * (n + 1) / 2
- 計算完整的總和
- 遍歷陣列:
- 對於陣列中的每個數字
num,執行total -= num
- 對於陣列中的每個數字
- 返回結果:
- 返回
total,即為缺失的數字
- 返回
例子說明#
nums = [3,0,1]
| 步驟 | n | total | num | total - num | 說明 |
|---|---|---|---|---|---|
| 初始化 | 3 | 6 | - | - | 計算完整總和 total = 6 |
| 第1輪 | 3 | 6 | 3 | 3 | total -= 3 |
| 第2輪 | 3 | 3 | 0 | 3 | total -= 0 |
| 第3輪 | 3 | 3 | 1 | 2 | total -= 1 |
| 最終結果 | - | 2 | - | - | 返回 total,缺失的數字是 2 |
完整程式碼#
java
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
// 計算完整的總和
int total = n * (n + 1) / 2;
// 遍歷陣列中的每個數字
for(int num : nums){
// 從 total 中減去該數字
total -= num;
}
// 返回缺失的數字
return total;
}
}時間複雜度#
- 時間複雜度:
O(n),其中 n 是陣列的長度,需要遍歷所有元素 - 空間複雜度:
O(1),只使用了常數個變數

