一、题目
Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2]
Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Constraints:
1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
Each element in nums appears exactly three times except for one element which appears once.
二、题解
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
//记录所有数每一位上为1的总数
vector<int> cnt(32,0);
for(auto x:nums){
for(int i = 0;i < 32;i++){
cnt[i] += (x >> i) & 1;
}
}
int res = 0;
for(int i = 0;i < 32;i++){
//不是3的倍数,说明该数在这一位上为1
if(cnt[i] % 3 != 0) res |= 1 << i;
}
return res;
}
};