It is not a big deal at the first sight: https://oj.leetcode.com/problems/single-number/
And my AC code is straightforward:
#include <unordered_set> using namespace std; typedef unordered_set<int> Myset; class Solution { public: int singleNumber(int A[], int n) { Myset set; for (int i = 0; i < n; i++) { int n = A[i]; if (set.find(n) == set.end()) set.insert(n); else set.erase(n); } return *set.begin(); } };
But I was completely shocked by the optimal solution:
class Solution { public: int singleNumber(int A[], int n) { int x = 0; for (int i = 0; i < n; i ++) x ^= A[i]; return x; } };
OMG, the charm of bit operations!