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

曾经做过一道水题找出除了一个数字之外,其他数字都有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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值