http://zhedahht.blog.163.com/blog/static/25411174201283084246412/
思路:
1. x & (-x)所得的结果即是x最后一位1所在的位置。
2. x = a ^ b ^ c, f(x) = x & (-x)
3. f(x^a)^f(x^b)^f(x^c) 结果必有一位是1,因为f(m)^f(n)结果为0或者为2个1
4. f(x^a)^f(x^b)^f(x^c)的第m位为1,则x^a, x^b, x^c必有1个或者3个第m位为1
5. 用反证法可得,x^a, x^b, x^c只有一个第m位为1
#include <iostream> #include <vector> using namespace std; int GetLastBit(int n) { return n & (-n); } void Get3Unique(vector<int>& data, vector<int>& unique) { if (data.size() < 3) return; int xor = 0; vector<int>::const_iterator iter; for (iter = data.begin(); iter != data.end(); ++iter) xor ^= *iter; int flag = 0; for (iter = data.begin(); iter != data.end(); ++iter) flag ^= GetLastBit(xor ^ *iter); flag = GetLastBit(flag); int first = 0; for (iter = data.begin(); iter != data.end(); ++iter) if (GetLastBit(*iter ^ xor) == flag) first ^= *iter; xor = 0; for (iter = data.begin(); iter != data.end(); ++iter) if (*iter != first) xor ^= *iter; flag = GetLastBit(xor); int second = 0, third = 0; for (iter = data.begin(); iter != data.end(); ++iter) if (*iter != first) { if (*iter & flag) second ^= *iter; else third ^= *iter; } unique.empty(); unique.push_back(first); unique.push_back(second); unique.push_back(third); }