找到数组中唯一的未配对元素

kar*_*ank 53 algorithm

埃森哲面试问题:

您已经获得了一个大小数组,2n+1其中包含n一对整数(可以是+ve,-ve0)和一个不成对的元素.

你怎么会找到不成对的元素?

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

cod*_*ict 97

采取XOR的所有元素.

这对将取消为

a XOR a = 0
Run Code Online (Sandbox Code Playgroud)

结果将是唯一不成对的元素

0 XOR a = a
Run Code Online (Sandbox Code Playgroud)

如果它可以摧毁阵列你可以XOR相邻的元素.完成后,数组的最后一个元素具有未配对的元素:

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

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

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

C函数做同样的事情:

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.
}
Run Code Online (Sandbox Code Playgroud)

  • 在形式上,xor是可交换的和关联的,这意味着初始输入被xored的顺序与最终结果无关. (17认同)
  • 不正确.不需要对元素进行排序.例如:1 2 3 1 3.在此示例中跟踪算法.当你全部消失时,你会得到2. (4认同)