這道題也很有意思,依舊是位運(yùn)算鳄逾,找出兩個(gè)不一樣的數(shù)稻轨,全部異或起來(lái)得到的是兩個(gè)不同數(shù)的異或結(jié)果,此時(shí)為1的位就代表著這兩數(shù)在這一位的值不同雕凹,那么就可以把原來(lái)的數(shù)組利用這一點(diǎn)分為兩類:這一位是1和這一位是0的殴俱,再利用構(gòu)造出來(lái)的只有這一位是1的數(shù)去與就可以分開各自異或各自的就行政冻。
他人解法
很慚愧,完全沒(méi)思路> <
class Solution
{
public:
vector<int> singleNumber(vector<int>& nums)
{
// Pass 1 :
// Get the XOR of the two numbers we need to find
int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
// Get its last set bit
diff &= -diff;
// Pass 2 :
vector<int> rets = {0, 0}; // this vector stores the two numbers we will return
for (int num : nums)
{
if ((num & diff) == 0) // the bit is not set
{
rets[0] ^= num;
}
else // the bit is set
{
rets[1] ^= num;
}
}
return rets;
}
};