背景
題目英文
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. “數組”類算法
- LeetCode實戰:三數之和
- LeetCode實戰:最接近的三數之和
- LeetCode實戰:求衆數
- LeetCode實戰:缺失的第一個正數
- LeetCode實戰:快樂數
- LeetCode實戰:尋找兩個有序數組的中位數
- LeetCode實戰:盛最多水的容器
- LeetCode實戰:刪除排序數組中的重複項
- LeetCode實戰:搜索旋轉排序數組
- LeetCode實戰:螺旋矩陣
- LeetCode實戰:螺旋矩陣 II
2. “鏈表”類算法
- LeetCode實戰:兩數相加
- LeetCode實戰:刪除鏈表的倒數第N個節點
- LeetCode實戰:合併兩個有序鏈表
- LeetCode實戰:合併K個排序鏈表
- LeetCode實戰:兩兩交換鏈表中的節點
- LeetCode實戰:旋轉鏈表
- LeetCode實戰:環形鏈表
3. “棧”類算法
4. “隊列”類算法
5. “遞歸”類算法
6. “字符串”類算法
7. “樹”類算法
8. “哈希”類算法
9. “搜索”類算法
10. “動態規劃”類算法
11. “回溯”類算法
12. “數值分析”類算法