Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
给定一个非空整数数组,除了其中一个元素外,其余每个元素均出现三次。找出这个只出现一次的元素。
位运算、状态机
0^a=a
、a^a=0
,即可求得结果;class Solution {
public:
int singleNumber(vector<int>& nums) {
int ret = 0;
for(int i=0; i<32; ++i){
int sum = 0;
for(int j=0; j>i) & 1;
}
ret |= (sum % 3)<return ret;
}
};
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ones = 0, twos = 0;
for(int i=0; ireturn ones;
}
};
bits[2]
来得到该返回元素,具体就不展开分析。class Solution {
public:
int singleNumber(vector<int>& nums) {
return singleNumber(nums, 3);
}
int singleNumber(vector<int>& nums, int _K) {
int K = _K - 1;
int bits[K] = {0};
for (int num : nums) {
for (int i = 0; i < K; i++) {
int mask = -1;
for (int j = 0; j < K; j++) if (j != i)
mask &= ~bits[j];
bits[i] = (bits[i] ^ num) & mask;
}
}
return bits[0];
}
};