Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
http://oj.leetcode.com/problems/single-number/
Solution:
Bit operation, use XOR. We know that A^A = 0, A^0 = A. Use a for loop to XOR every element in the array and get the single one.
https://github.com/starcroce/leetcode/blob/master/single_number.cpp
// 52 ms for 14 test cases
class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int ans = 0;
for(int i = 0; i < n; i++) {
ans ^= A[i]; // ^ = XOR, a^a = 0, a^a^b = b
}
return ans;
}
};