异或找到一个阵列重复 [英] XOR to find Duplicates in an array

查看:299
本文介绍了异或找到一个阵列重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了在这个线程这个问题的解决方案 - > <一个href="http://stackoverflow.com/questions/2605766/how-to-find-a-duplicate-element-in-an-array-of-shuffled-consecutive-integers/2612318#2612318">How找到重复的元素在洗牌连续整数数组?

I have seen the solution for this problem in this thread -> How to find a duplicate element in an array of shuffled consecutive integers?

但问题我现在有是从它的小变化。

But the problem I am now having is little varied from it.

int arr[10] = {1,2,3,4,5,6,7,8,4,9};
    int a= 0;
    for(int i=0;i<10;i++) {
     a= a^ arr[i] ^i;
    }
    cout<<a;

考虑以上提到的code段。事情做工精细,因为它是。但是,当我加个0,以上述数组一样, INT改编[11] = {0,1,2,3,4,5,6,7,8,4,9}; 我没有得到适当的重复的元素。有人可以纠正我,我想提出的覆辙?

Consider the above mentioned code snippet. Things work fine as it is. But when I add a 0 to the above mentioned array like, int arr[11] = {0,1,2,3,4,5,6,7,8,4,9}; I am not getting the proper duplicate element. Can somebody correct me the mistake I am making here?

推荐答案

诀窍依靠1和N之间的值。如果数字在其他一些范围,你就必须补偿他们。

The trick relies on the values being between 1 and n. If the numbers are in some other range you'll have to offset them.

static const int n = 11;
int arr[n] = {0,1,2,3,4,5,6,7,8,4,9};
int offset = 1;
int a= 0;
for(int i=0;i<n;i++) {
 a= a^ (arr[i]+offset) ^i;
}
cout<< (a-offset);

这篇关于异或找到一个阵列重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆