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.
題意給定一個非空整數數組,除了某個元素只出現一次以外,其餘每個元素均出現了三次。找出那個只出現了一次的元素。你的算法應該具有線性時間複雜度。你可以不使用額外空間來實現嗎?示例 1:
輸入: [2,2,3,2]
輸出: 3
示例 2:
輸入: [0,1,0,1,0,1,99]
輸出: 99
class Solution {
public:
int singleNumber(vector<int>& nums) {int res = 0;
for(int i = 0; i < 32; i++){
int sum = 0;
for(int num: nums)
if((num >> i) & 1)
sum++;
if(sum % 3)
res |= 1 << i;
}
return res;
}
};