快轉到主要內容
leetcode 268 - Missing Number

leetcode 268 - Missing Number

·
類別 
Leetcode
標籤 
Java Leetcode Easy Array Problem Blind75
Eason Chiu
作者
Eason Chiu
一個不做筆記就容易忘記的工程師
目錄

題目
#

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)

  1. 計算完整的總和 total = n * (n + 1) / 2
  2. 遍歷陣列中的每個數字,從 total 中減去該數字
  3. 最後 total 的值即為缺失的數字

步驟
#

  • 初始化:
    • 計算完整的總和 total = n * (n + 1) / 2
  • 遍歷陣列:
    • 對於陣列中的每個數字 num,執行 total -= num
  • 返回結果:
    • 返回 total,即為缺失的數字

例子說明
#

nums = [3,0,1]

步驟ntotalnumtotal - num說明
初始化36--計算完整總和 total = 6
第1輪3633total -= 3
第2輪3303total -= 0
第3輪3312total -= 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),只使用了常數個變數

相關文章

leetcode 217 - Contains Duplicate
類別 
Leetcode
標籤 
Java Leetcode Easy Array Problem Blind75
leetcode 121 - Best Time to Buy and Sell Stock
類別 
Leetcode
標籤 
Java Leetcode Easy Array Problem Blind75
leetcode 125 - Valid Palindrome
類別 
Leetcode
標籤 
Java Leetcode Easy String Problem Two Pointers Problem Blind75