找到数组中唯一未配对的元素 [英] find the only unpaired element in the array

查看:25
本文介绍了找到数组中唯一未配对的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

埃森哲面试问题:

你得到了一个大小为 2n+1 的数组,它有 n 对整数(可以是 +ve, -ve0) 和一个未配对的元素.

You have been given an array of size 2n+1 that have n pair of integers (can be +ve, -ve or 0) and one unpaired element.

如何找到未配对的元素?

How would you find the unpaired element?

配对意味着重复.所以 (3,3) 是一对而 (3,-3)不是一对.

Pair means duplicate. So (3,3) is a pair and (3,-3) is not a pair.

推荐答案

对所有元素进行 XOR.

配对将抵消为

a XOR a = 0

并且结果将是唯一未配对的元素

and the result will be the only unpaired element as

0 XOR a = a

如果可以销毁数组,您可以XOR 相邻元素.完成后,数组的最后一个元素具有未配对的元素:

If its okay to destroy the array you can XOR adjacent elements. Once done the last element of the array has the unpaired element:

N = Num of elements in array.
for( i=1 to N )
   arr[i] ^= arr[i-1];    
print arr[N-1]

如果不能销毁数组,你可以使用一个变量来保存结果:

If its not okay to destroy the array, you can make use of a variable to hold the result:

N = Num of elements in array.
Unpaired = arr[0];
for( i=1 to N )
   Unpaired = Unpaired ^ arr[i];    
print Unpaired

C 函数做同样的事情:

C function to do the same:

int findUnpaired(int *arr,int len) {
 int i;                  // loop counter.
 int unpaired;           // to hold the unpaired element.

 unpaired = arr[0];      // initialize it with the 1st array ele.

 for(i=1;i<len;i++) {    // loop for all remaining elements.
    unpaired ^= arr[i];  // XOR each element with the running XOR.
 }
 return unpaired;        // return result.
}

这篇关于找到数组中唯一未配对的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆