您的位置:首页 > 其它

数组元素奇偶次数问题

2010-12-09 10:22 85 查看
给定一个数组,大小为n,其中有一个元素出现一次,其他元素都出现两次,编写程序返回仅出现一次的元素。
比如 1 2 2 3 1 3 4 5 4,返回5
方法很多,比较高效的方法应该是使用异或,依据:X异或X=0,0异或X等于X,而且满足交换律。

#include <iostream>
#include <cassert>
using namespace std;
int FindOddElement(const int* a,int n)
{
assert(a&&n>0);
int temp=a[0];
for(int i=1;i<n;i++)
{
temp^=a[i];
}
return temp;
}
int main()
{
int test[]={1,2,6,7,2,1,6};
int size = sizeof(test)/sizeof(test[0]);
cout<<FindOddElement(test,size);
cout<<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: