XOR 查找数组中的重复项
我已经在这个线程中看到了这个问题的解决方案 -> 如何在打乱顺序的连续整数数组中找到重复元素?
但我现在遇到的问题与此几乎没有什么不同。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该技巧依赖于 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.
我猜这可能与 i 值与 arr[i] 相同这一事实有关,
就像这样做:
等于 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:
which equals 00000000
and I may be thinking incorrectly but wouldn't that screw up the process?
我想我明白发生了什么。您可能将循环更改为,
因为您向循环添加了额外的元素。问题是它没有与 10 进行异或,而 10 不是数组中的数字。因此,该算法停止工作。
现在,它对 0 到 9 的数字进行 XOR 两次(等于 0),并再对 4 进行一次异或,因此结果应该是 4。
I think i see what happened. you probably changed the loop to be
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.
now, its XORing nums from 0 to 9 twice (which equals zero) and 4 an additional time, so the result should be 4.