LeetCode實戰:只出現一次的數字

背景


題目英文

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

題目中文

給定一個非空整數數組,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。

說明

你的算法應該具有線性時間複雜度。 你可以不使用額外空間來實現嗎?

示例 1:

輸入: [2,2,1]
輸出: 1

示例 2:

輸入: [4,1,2,1,2]
輸出: 4

算法實現

方式一:利用“哈希”的方法

public class Solution
{
    public int SingleNumber(int[] nums)
    {
        HashSet<int> h = new HashSet<int>();
        for (int i = 0; i < nums.Length; i++)
        {
            if (h.Contains(nums[i]))
            {
                h.Remove(nums[i]);
            }
            else
            {
                h.Add(nums[i]);
            }
        }
        return h.ElementAt(0);
    }
}

方式二:利用位運算的方法

A: 0 0 0 0 1 1 0 0
B: 0 0 0 0 0 1 1 1

A^B: 0 0 0 0 1 0 1 1
B^A: 0 0 0 0 1 0 1 1

A^A: 0 0 0 0 0 0 0 0
A^0: 0 0 0 0 1 1 0 0

A^B^A: = A^A^B = B = 0 0 0 0 0 1 1 1

"異或"操作滿足交換律和結合律。

public class Solution
{
    public int SingleNumber(int[] nums)
    {
        int result = 0;
            
        for (int i = 0; i < nums.Length; i++)
        {
            result ^= nums[i];
        }
        return result;
    }
}

實驗結果

方式一:利用“哈希”的方法

  • 狀態:通過
  • 16 / 16 個通過測試用例
  • 執行用時: 136 ms, 在所有 C# 提交中擊敗了 98.86% 的用戶
  • 內存消耗: 26.4 MB, 在所有 C# 提交中擊敗了 5.34% 的用戶

提交結果

方式二:利用位運算的方法

  • 狀態:通過
  • 16 / 16 個通過測試用例
  • 執行用時: 144 ms, 在所有 C# 提交中擊敗了 91.76% 的用戶
  • 內存消耗: 25.4 MB, 在所有 C# 提交中擊敗了 11.39% 的用戶

提交結果


相關圖文

1. “數組”類算法

2. “鏈表”類算法

3. “棧”類算法

4. “隊列”類算法

5. “遞歸”類算法

6. “字符串”類算法

7. “樹”類算法

8. “哈希”類算法

9. “搜索”類算法

10. “動態規劃”類算法

11. “回溯”類算法

12. “數值分析”類算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章