码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-07 03:06:48      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:io   for   amp   type   ef   程序   algorithm   return   

曾经做过一道水题找出除了一个数字之外,其他数字都有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;
}

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

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

标签:io   for   amp   type   ef   程序   algorithm   return   

原文地址:http://blog.csdn.net/u013923947/article/details/38409915

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!