对于两个数,对于结果中,剩余bit1来异或区分。
下面的解法,非常精简:
int lastBitOf1(int number) { return number & ~(number - 1); } void getTwoUnique(vector<int>::iterator begin, vector<int>::iterator end, vector<int>& unique) { int xorResult = 0; for(vector<int>::iterator iter = begin; iter != end; ++iter) xorResult ^= *iter; int diff = lastBitOf1(xorResult); int first = 0; int second = 0; for(vector<int>::iterator iter = begin; iter != end; ++iter) { if(diff & *iter) first ^= *iter; else second ^= *iter; } unique.push_back(first); unique.push_back(second); }
对于有三个数的情况,复杂一些:
要用到异或结果跟所有数异或的最后一位,再异或。如下:
http://blog.csdn.net/sunmenggmail/article/details/8035008
- for(iter = numbers.begin(); iter != numbers.end(); ++iter)
- flags ^= lastBitOf1(xorResult ^ *iter);
- flags = lastBitOf1(flags);