问题描述
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
解题思路
该问题给了我们一组数,其中只有一个数只出现了一次,其他的都出现了三次,要我们把只出现了一次的数找出来。我们可以这样思考,将数组中的每个数字用二进制表示,并且统计每一位上所有元素的和,除了只出现了一次的,其他的数都出现了三次,那么如果不包括我们要求的数,其他的数加起来在每一位上都是3的倍数,随意我们只要用每一位上的数字以3取余,就是我们要求的数在该位的值。最后在将二进制转为十进制即可。
代码展示
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class Solution {
public:
int singleNumber(vector<int>& nums) {
int count[32]={0};
int result=0;
for(int i=0;i<32;i++){
for(int j=0;j<nums.size();j++){
count[i]+=((nums[j]>>i)&1);
count[i]=count[i]%3;
}
result|=(count[i]<<i);
}
return result;
}
};
int main(){
int n;
vector<int> nums;
cout<<"请输入向量长度:";
cin>>n;
int a;
for(int i = 0;i<n;i++){
cin>>a;
nums.push_back(a);
}
Solution solution;
int result=solution.singleNumber(nums);
cout<<result<<endl;
}
运行结果