You can think of a 3nary XOR operation (call it XOR3 ), which works in base 3 instead of base 2 and simply accepts each 3nary digit modulo 3 (when a regular XOR accepts a 2nary digit modulo 2).
Then, if you XOR3 all numbers (converting them to 3nary first) this way, you will be left with a unique number (in base 3, so you will need to return it).
The complexity is not exactly linear, because transitions from / to base 3 require additional logarithmic time. However, if the range of numbers is constant, the conversion time is also constant.
C ++ code (intentionally verbose):
vector<int> to_base3(int num) { vector<int> base3; for (; num > 0; num /= 3) { base3.push_back(num % 3); } return base3; } int from_base3(const vector<int> &base3) { int num = 0; for (int i = 0, three = 1; i < base3.size(); ++i, three *= 3) { num += base3[i] * three; } return num; } int find_unique(const vector<int> &a) { vector<int> unique_base3(20, 0);
source share