一个整型数组里除了两个不同数字之外,其它的数字都出现了两次。请写程序找出这两个只出现一次的数字。

来源:互联网 发布:知乎 红尘来去一场空 编辑:程序博客网 时间:2024/04/30 13:47

曾经做过一道水题找出除了一个数字之外,其他数字都有2个。直接异或 最后结果就是那个数。

现在变成存在2个不一样的数字,假设成x,y,那么可以O(n)求出x^y,因为x,y不同,所以异或的结果不为0,看成2进制数,那么找到第一位为1 的位置,将这个位置设置为划分点,数组里所有这个位置为1 的异或一次,所有为0的再异或一次,最终求出的两个即为两个独特的数字。

#include <stdio.h>#include <string.h>#include <algorithm>#include <math.h>using namespace std;typedef long long LL;const int MAX=0x3f3f3f3f;const int maxn = 10001;int a[maxn], n;int main(){    scanf("%d", &n);    for(int i = 1; i <= n; i++) scanf("%d", &a[i]);    int t = 0, cnt = 0;    for(int i = 1; i <= n; i++) t ^= a[i];    int tmp = t;    while(tmp % 2 == 0) {        cnt++;        tmp >>= 1;    }    int x = 0, y = 0;    for(int i = 1; i <= n; i++)        if((a[i] >> cnt)%2) x ^= a[i];    for(int i = 1; i <= n; i++)        if((a[i] >> cnt)%2 == 0) y ^= a[i];    printf("%d %d\n", x, y);        return 0;}

0 0