您的位置:首页 > 其它

[九度][何海涛] 数组中只出现一次的数字

2012-11-23 11:28 246 查看
题目描述:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。输入:
每个测试案例包括两行:
第一行包含一个整数n,表示数组大小。2<=n <= 10^6。
第二行包含n个整数,表示数组元素,元素均为int。
输出:对应每个测试案例,输出数组中只出现一次的两个数。输出的数字从小到大的顺序。样例输入:
8
2 4 3 6 3 2 5 5

样例输出:
4 6


#include <iostream>
#include <cstdio>
using namespace std;

int a[1000000];

int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
int res = 0;
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
res ^= a[i];
}

int mask = 1;
while((mask & res) == 0)
mask = mask << 1;

int num1 = 0;
int num2 = 0;
for(int i = 0; i < n; i++)
if ((a[i] & mask) == 0)
num1 ^= a[i];
else
num2 ^= a[i];

if (num1 > num2)
{
int t = num1;
num1 = num2;
num2 = t;
}

cout << num1 << ' ' << num2 << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: