题:2n+1长度的整型数组中,有且仅有一个元素不与其他元素相同,试用最小的资源找出该元素。
使用位操作,两个相同的数字异或运算之后结果为0的特性,通过异或运算找出2n+1长度的数字数组中的不成对的数字。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using namespace std;
int getdiff(int data[], int n) {
int i, j=0;
for(i=0; i<n; i++) {
j ^= data[i];
}
return j;
}
int main() {
int arr[] = {1,3,5,7,9,1,3,5,7,9,13};
int res = getdiff(arr, 11);
cout<<"diff in arr[1,3,5,7,9,1,3,5,7,9,13] is: "<<res<<endl;
return 0;
}
延伸:在2n长度的整型数组中,找出有且仅有的两个不成对数字。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using namespace std;
void getdiffTwo(int *arr, int n, int *res) {
int i, j=0, flag=1;
for(i=0; i<n; i++) {
j ^= arr[i];
}
// 找出这两个不成对数字中位上值不同的最低位
while(!(j & flag)) {
flag <<= 1;
}
// 找出其中一个不成对的数
for(i=0; i<n; i++) {
if(flag & arr[i]) {
res[0] ^= arr[i];
}
}
// 另一个也就显而易见了
res[1] = j ^ res[0];
}
int main() {
int arr[] = {1,3,5,7,9,1,3,5,7,9,11,13};
int n = 12;
int res[] = {0, 0};
getdiffTwo(arr, n, res);
cout<<"two diff in arr is: "<<res[0]<<" and "<<res[1]<<endl;
return 0;
}