题目链接:点击打开链接
思路:线性复杂度且不能用额外的空间,
参考了这位大佬的博客 http://blog.youkuaiyun.com/hunyxv/article/details/69397724
给定一个数组 A,除了一个数出现一次之外,其余数都出现三次。找出出现一次的数。
如:{1,2,1,2,1,2,7},找出 7。
你的算法只能是线性时间的复杂度,并且不能使用额外的空间哦~
输入格式
第一行输入一个数n(1≤n≤500),代表数组的长度。
接下来一行输入 n 个 int 范围内(−2147483648…2147483647)的整数,表示数组 A。保证输入的数组合法。
输出格式
输出一个整数,表示数组中只出现一次的数。
样例输入
4
0 0 0 5
样例输出
5
本来以为很简单……..以为用for循环就能搞定,但 算法复杂度要求…..
想了好长时间,后来在网上看了别人的解法才学会,所以记下笔记。
由于除了一个特殊的数外,其他的数都有 3 个,使用二进制的位运算,既然其他每次数都出现3次,那么如果针对每一位求和并对3取余,那么那些出现3次的数字在这一位的和对3取余后肯定是0。如:
1: 0 0 0 1
2: 0 0 1 0
1: 0 0 0 1
2: 0 0 1 0
1: 0 0 0 1
2: 0 0 1 0
7: 0 1 1 1
─────────
0 1 4 4
0 1 4 4 每位除以3取余 得 0 1 1 1 => 7
AC代码:
/*
2017年9月10日09:22:01
计蒜客15 单独的数字
位运算
AC
*/
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
int cnt[32];
int main(){
int n,ans;
scanf("%d",&n);
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
for(int j=0;j<32;j++){
cnt[j]+=x>>j &1;
cnt[j]%=3;
}
/*
for(int i=0;i<32;i++){
printf("%d ",cnt[i]);
}printf("\n");
*/
}
ans=0;
for(int i=0;i<32;i++){
ans+=cnt[i]<<i;
}
printf("%d\n",ans);
return 0;
}