51Nod 2107 二个奇数次 c/c++题解

题目描述

输入一个长度为n的数组,考虑所有不同的数字,有且只有2个数字出现了奇数次。
比如对于1 2 3 1 2 3 1 2,我们考虑所有不同的数字1 2 3,有且只有1,2出现了奇数次(均为3次)
输出这两个出现了奇数次的数字。
先输出这两个数字中较小的,再输出较大的。
1 <= n <= 100000
1 <= a[i] <= 10^9
输入
第一行一个整数n,
接下来一行n个整数,表示输入的数字。
输出
一行2个数字,表示出现了奇数次的数字,先输出小的,再输出大的。
输入样例
8
1 2 3 1 2 3 1 2
输出样例
1 2

题解:

方法1:map的应用

方法2:位运算的性质
有点类似于一个奇数次,只是要稍作处理即可:
n个数字中有两个数字出现了奇数次,其他的数字都是偶数次出现,
首先把n个数字异或一遍得到xo,
然后求出xo对应二进制数从右往左数直到遇到1,有多少个0
我先假设x1,x2是出现了奇数次的数
这道题目:一个奇数次可知,x1和其他n-2个数(不包括x2)异或一次,得到的还是x1,然后x1再和x2异或一次,就得到了xo,xo的从右往左数第一个1,一定由于x1和x2在那个位置的数不同形成的(异或:相异为1),
所以可以把n个数分为两组,一组是那一位为1的,一组是那一位为0的,那么x1和x2一定在不同的组,所以其他的数都是出现了偶数次,那么每一组的数也一定是 偶数个+x1 或者偶数个+x2,
然后对每一组异或,得到的就是x1和x2两个数了,再比较谁大谁小即可。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n;
int a[MAX];
//map <int,int> mp;

int main()
{
    /*
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    */

    while(cin >> n)
    {
        for(int i = 0; i < n; i++)
        {
            cin >> a[i];
            //mp[a[i]]++;
        }
        /* 1. map法
        for(auto it = mp.begin(); it != mp.end(); it++)
        {
            if(it->second % 2 != 0)
            {
                cout << it->first << " ";
            }
        }
        cout << endl;
        */
        /* 2. 异或法 */
        int xo = 0;
        for(int i = 0; i < n; i++)
        {
            xo ^= a[i];
        }
        int k = 0;
        while(((xo >> k) & 1) == 0) k++;
        int t1 = 0;
        int t0 = 0;
        for(int i = 0; i < n; i++)
        {
            if((a[i] >> k) & 1)
            {
                // 从右往左数第k位为1
                t1 ^= a[i];
            }
            else
            {
                // 从右往左数第k位为0
                t0 ^= a[i];
            }
        }
        if(t1 < t0)
        {
            cout << t1 << " " << t0 << endl;
        }
        else
        {
            cout << t0 << " " << t1 << endl;
        }
    }


    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值