[转]数组中只出现一次的两个数字

本文介绍了一种使用C++进行快速解码的方法,通过位运算找到两个唯一出现一次的数字。代码中利用了XOR运算的特性,先将所有数字进行XOR得到一个异或结果,然后找出该结果中最右边的1对应的位,以此位作为划分标准,将原始数组分为两组,分别进行XOR运算得到最终的两个数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:https://www.cnblogs.com/yyxayz/p/4067529.html
示例代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 5000050;

// 快读
inline int in()
{
    char ch;
    int a=0;
    while(!(((ch=getchar())>='0')&&(ch<='9')));  //利用getchar读入,速度快。
    a*=10;a+=ch-'0';
    while(((ch=getchar())>='0')&&(ch<='9'))a*=10,a+=ch-'0';  //而后用ASCII码转为int 类型
    return a;
}

int n, a[maxn], b[maxn], nb = 0, c[maxn], nc = 0;

int main() {
    n = in();
    for (int i = 0; i < n; i ++) a[i] = in();
    int t = 0;
    for (int i = 0; i < n; i ++) t ^= a[i];
    int p = 1;
    while (!(t&p)) p <<= 1;
    for (int i = 0; i < n; i ++) {
        if (a[i] & p) b[nb++] = a[i];
        else c[nc++] = a[i];
    }
    int t1 = 0;
    for (int i = 0; i < nb; i ++)
        t1 ^= b[i];
    int t2 = 0;
    for (int i = 0; i < nc; i ++)
        t2 ^= c[i];
    if (t1 > t2) swap(t1, t2);
    printf("%d %d\n", t1, t2);
    return 0;
}

转载于:https://www.cnblogs.com/zifeiy/p/10709218.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值