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?
Test cases:
1. [1, 2, 2, 3, 1]
Corner cases:
1. [1]
2. [0]
Solution 1:
Data structure:
hash table
Steps:
1. For each element, if not in the set, insert it; otherwise, erase it.
2. Return the only element in the set.
Complexity:
Runtime: O(n)
Space: O(n)
Code:
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_set<int> my_set;
for (int num : nums) {
if (my_set.find(num) != my_set.end()) {
my_set.erase(num);
} else {
my_set.insert(num);
}
}
return *my_set.begin();
}
};
Solution 2:
Data structure:
Bit Manipulation
steps:
1. For each element, do XOR.
Complexity:
Runtime: O(n)
Space: O(1)
Code:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (int num : nums) res = res^num;
return res;
}
};
Things to learn:
1. Be familiar with the bit manipulation operations.
2. num ^ num = 0.