Unique duplicate Element
Problem description: Set ~ 1000 is placed in an array containing 1001 elements. Only one unique element is repeated, and all other elements appear once. Design an algorithm to find out the unique and repeated element. Each array element must be accessed only once and cannot use auxiliary storage space.
Solution 1: Based on the topic description, you only need to sum the number of 1001 in the array to get sum0, And then subtract the sum of 1 to 1000 and sum1 to get the unique repeated number.
Reference code:
# Include <bits/stdc ++. h> using namespace std; int main () {srand (time (NULL); int pos = rand () % 1002; int num = rand () % 1002; cout <"random numbers:" <num <endl; int sum0 = 0; int sum1 = 0; for (int I = 1; I <= 1000; I ++) {if (I = pos) {sum0 + = num; sum0 + = pos;} else {sum0 + = I;} sum1 + = I ;} cout <"unique duplicate number:" <sum0-sum1 <endl ;}
GCC running result:
Solution 2:
This method is based on the difference or a ^ B ^ a = B; then we can make the occurrence of two times more than once, and the appearance of one more time for the same or, that is, a ^ B ^ a ^ B =;
(Because a ^ B ^ a = B ^ a ^ B =)
Reference code:
# Include <bits/stdc ++. h> using namespace std; int findRepeat (const int a []) {int temp = a [0]; for (int I = 1; I <1001; I ++) {temp ^ = I; temp ^ = a [I];} return temp;} int main () {srand (time (NULL); int num = rand () % 1002; cout <"random number:" <num <endl; int a [1001]; memset (a, 0, sizeof ()); a [0] = num; for (int I = 1; I <1001; I ++) {a [I] = I ;} cout <"the only repeated number is:" <findRepeat (a) <endl ;}
GCC running result:
We hope to find other solutions.
Reprinted Please note: http://www.cnblogs.com/zpfbuaa