class Solution {
public:
int singleNumber(vector<int>& nums) {
//典型的异或运算
int res = 0;
for (int i : nums)
{
res ^= i;
}
return res;
}
};
这里插入一点题外话:
其实实现两个数的交换用位运算也很方便:
void swap(int&a, int&b)
{
a = a^b;
b = b^a;
a = a^b;
}
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int length = nums.size();
if (length <= 1)
return{};
int result_ExclusiveOR = 0;
for (int i : nums)
{
result_ExclusiveOR ^= i;
}
//两个数不同,那么它们必然有一位是不同的,所以两个不同的数的这一位异或的结果为1
int index = find_first_index_of_bit_1(result_ExclusiveOR);
//按第index位分成两堆
int temp1 = 0, temp2 = 0;
for (int i : nums)
{
if (isBit1(i, index))
{
temp1 ^= i;
}
else
{
temp2 ^= i;
}
}
vector<int>res;
res.push_back(temp1);
res.push_back(temp2);
return res;
}
int find_first_index_of_bit_1(int number)
{
int index = 0;
while (((number & 1) == 0) && index<8 * sizeof(int))
{
index++;
number >>= 1;//右移一位
}
return index;
}
bool isBit1(int number, int index)
{
if (((number >> index) & 1) == 0)//注意&优先级比>>高
return false;
return true;
}
};
这个思路就不是很好想到了:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int a = 0, b = 0;
for (auto num : nums)
{
a = (a ^ num) & ~b;
b = (b ^ num) & ~a;
}
return a;
}
};