51Nod 2106 一个奇数次 c/c++题解

题目描述

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

题解:

解法1:直接用map记录下数组中每个数字出现的次数,然后判断哪个数字出现了奇数次即可。

解法2:一个数(十进制)异或两次另一个数(十进制),结果不变,原因:两个数(二进制)异或的性质,不管是0还是1,异或同一个二进制数异或两次,结果不变,十进制数就是由二进制数组成的,二进制数都没有变,那十进制肯定也不变。
因此,n个数中只有一种数字出现了奇数次,其他的数字都出现偶数次,那么从这种数字(出现了奇数次)中抽一个出来,去异或其他的数字,反正其他的数字都是出现了偶数次(包括了原本出现奇数次的,现在抽出一个也变成了偶数次),那么异或的结果还是这个数字本身,所以其实只要把所有的数字异或一遍即可。

代码:

#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;
map <int,int> mp;

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

    while(cin >> n)
    {
        mp.clear();
        int x;
        int t = 0;
        for(int i = 0; i < n; i++)
        {
            cin >> x;
            //mp[x]++;// 方法1: 使用STL的map
            t ^= x;// 方法2: 异或所有的数字
        }
        //cout << t << endl;
        /*
        for(auto it = mp.begin(); it != mp.end(); it++)
        {
            if(it->second % 2 != 0)
            {
                cout << it->first << endl;
                break;
            }
        }*/

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值