https://leetcode-cn.com/problems/single-number/
https://leetcode-cn.com/problems/single-number-ii/
https://leetcode-cn.com/problems/single-number-iii/
思路:32位表示位,统计每位的个数,%3的余数则是结果
int singleNumber(vector<int>& nums) {
if (nums.size() == 1) {
return nums[0];
}
int sum = nums[0];
for (int i = 1; i < nums.size(); i++) {
sum = sum ^ nums[i];
}
return sum;
}
int singleNumber(vector<int>& nums) {
if (nums.size() == 1) {
return nums[0];
}
vector<int> dp(33, 0);
int res = 0;
for (int i = 0;i < 32; i++) {
int sum = 0;
for (int j = 0;j < nums.size(); j++) {
//>>和/相除有区别,暂时未知道原因
sum += nums[j] >> i & 1;
}
res += (sum % 3) << i;
}
return res;
}
vector<int> singleNumber(vector<int>& nums) {
vector<int> res;
long cnt = nums[0];
for (int i = 1;i < nums.size(); i++) {
cnt = cnt ^ nums[i];
}
vector<int> temp;
temp.push_back(0);
temp.push_back(0);
//获取最后一个1
long k = cnt & (-cnt);
for (int i = 0; i < nums.size(); i++) {
if (nums[i] & k) {
temp[0] = temp[0] ^ nums[i];
} else {
temp[1] = temp[1] ^ nums[i];
}
}
res.push_back(temp[0]);
res.push_back(temp[1]);
return res;
}