Problem
Problem page: https://leetcode.com/problems/single-number/
Topics: Hash Table, Bit Manipulation
Difficulty: Medium
Similar problems: (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?
Analysis
I think there was a similar problem in Beauty of Programming too. The trick is XOR (XOR is commutative). If you know that, you can solve it right away. If you don't, you can rack your brain and still not come up with it. Of course, you could also insert all the elements into a hashmap/map or something similar in one pass and find the one that appears only once, but I imagine the interviewer wouldn't be too happy. There are plenty of tricks to bit manipulation, and I still have a lot to learn.
See also Single Number II.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-single-number/
