使用异或的特性。
a^a = 0
;a^0 = a
;(a^b)^c = a^(b^c)
。
以上图例题为例,
2^2^1 = 0^1 = 1
4^1^2^1^2 = 4^(1^1)^(2^2) = 4^0^0 = 4
当然此题也可以使用hash表来做。
int singleNumber(vector<int>& nums) {
int res=0;
for(int n:nums)
res^=n;
return res;
}
使用异或的特性。
a^a = 0
;a^0 = a
;(a^b)^c = a^(b^c)
。2^2^1 = 0^1 = 1
4^1^2^1^2 = 4^(1^1)^(2^2) = 4^0^0 = 4
int singleNumber(vector<int>& nums) {
int res=0;
for(int n:nums)
res^=n;
return res;
}