題目
原題頁面:https://leetcode.com/problems/single-number/
題目型別:Hash Table, Bit Manipulation
難度評價:Medium
類似題目:(M) Single Number II, (M) Single Number III, (M) Missing Number, (H) Find the Duplicate Number
Given an 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?
分析
程式設計之美上好像也出現過類似的題目。關鍵是異或操作(異或支援交換律),知道的人立馬能做出來,不知道的人想破腦袋也想不出這個方法。當然用hashmap/map之類的把所有元素插一遍也能找出這個只出現過一次的元素,但是想必面試官不會很開心。位操作還是有很多技巧的,還需要繼續深入學習。
此外還可以參考Single Number II。
程式碼
1 | class Solution: |
