查找数组中未出现两次的整数
问题内容:
我正在尝试解决此问题:在整数数组中,所有数字都发生两次,除了单个数字发生一次。
一个简单的解决方案是对数组进行排序,然后测试是否重复。但是我正在寻找时间复杂度为O(n)的更好的解决方案。
问题答案:
您可以在整个阵列上使用“异或”运算。每对数字将相互抵消,使您获得所寻求的价值。
int get_orphan(int const * a, int len)
{
int value = 0;
for (int i = 0; i < len; ++i)
value ^= a[i];
// `value` now contains the number that occurred odd number of times.
// Retrieve its index in the array.
for (int i = 0; i < len; ++i)
{
if (a[i] == value)
return i;
}
return -1;
}