题目描述如下:
方法一:
位运算
原理:两个相同的数x,x进行按位与操作,即x^x,结果为0,某个数y与0按位与则结果为原数,即y^0=y;
so,某个数y,遇到一个数x,y^x,当y^x再次遇到x时就会把x抵消掉,按照这种操作,最后剩下的就是出现次数为1的数了
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 int main(void) 6 { 7 int n; 8 while(~scanf("%d",&n) && n!=0) 9 { 10 int x,temp=0; 11 for(int i=1;i<=n;i++) 12 { 13 scanf("%d",&x); 14 temp=temp^x; 15 } 16 printf("%d\n",temp); 17 } 18 19 return 0; 20 }
方案二:
STL之map容器
关于map基本操作参考如下链接:
https://www.jianshu.com/p/0cd5cca5c4e0
map就像是python里面的字典有一组键值对,key-value
key由const修饰,故key不可改变,此题中出现的数字可以作为key,次数作为value,形成对应关系
1 #include <map> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 6 int main(void) 7 { 8 int n,a; 9 10 while(~scanf("%d",&n) && n!=0) 11 { 12 map<int,int>m; 13 map<int,int>::iterator it; 14 for(int i=1;i<=n;i++) 15 { 16 scanf("%d",&a); 17 m[a]++; 18 } 19 20 for(it=m.begin();it!=m.end();it++) 21 { 22 if(it->second==1) 23 { 24 printf("%d\n",it->first); 25 break; 26 } 27 } 28 } 29 30 return 0; 31 }
据说,因为数据小,所以可以用位运算,否则也会超时,数据大时用map会更省时。但是针对本题,还是位运算省时;(';'程序员般结尾23333)