我正在尝试解决这个问题:
在整数数组中,除了单个数字只出现一次之外,所有数字都恰好出现两次。
一个简单的解决方案是对数组进行排序,然后测试不重复。但我正在寻找时间复杂度为 O(n) 的更好的解决方案。
您可以对整个数组使用“xor”运算。每对数字都会相互抵消,留下您想要的值。
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)