问题
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?
回答1:
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);
回答2:
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?
回答3:
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.
来源:https://stackoverflow.com/questions/8018086/xor-to-find-duplicates-in-an-array