XOR 查找数组中的重复项

发布于 2024-12-13 16:56:05 字数 510 浏览 2 评论 0原文

我已经在这个线程中看到了这个问题的解决方案 -> 如何在打乱顺序的连续整数数组中找到重复元素?

但我现在遇到的问题与此几乎没有什么不同。

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;

考虑上面提到的代码片段。一切都按原样运作良好。但是当我向上述数组添加 0 时,例如 int arr[11] = {0,1,2,3,4,5,6,7,8,4,9};我没有得到正确的重复元素。有人可以纠正我在这里犯的错误吗?

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;

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

把时间冻结 2024-12-20 16:56:05

该技巧依赖于 1 到 n 之间的值。如果数字在其他范围内,则必须抵消它们。

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);

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);
潇烟暮雨 2024-12-20 16:56:05

我猜这可能与 i 值与 arr[i] 相同这一事实有关,

就像这样做:

00000001 ^ 00000001

等于 00000000

我可能想错了,但这不会搞砸这个过程吗?

I'm guessing it could have to do with the fact that the i value would then be the same as arr[i]

thats like doing:

00000001 ^ 00000001

which equals 00000000

and I may be thinking incorrectly but wouldn't that screw up the process?

月朦胧 2024-12-20 16:56:05

我想我明白发生了什么。您可能将循环更改为,

for(int i=0; i<11; i++)
  ...

因为您向循环添加了额外的元素。问题是它没有与 10 进行异或,而 10 不是数组中的数字。因此,该算法停止工作。

int arr[11] = {0,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;
}
a = a^arr[10];

cout<<a;

现在,它对 0 到 9 的数字进行 XOR 两次(等于 0),并再对 4 进行一次异或,因此结果应该是 4。

I think i see what happened. you probably changed the loop to be

for(int i=0; i<11; i++)
  ...

since you added an extra element to the loop. the problem is that it's not XORing with 10, which is not a number in your array. So, the algorithm stops working.

int arr[11] = {0,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;
}
a = a^arr[10];

cout<<a;

now, its XORing nums from 0 to 9 twice (which equals zero) and 4 an additional time, so the result should be 4.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文