gpt4 book ai didi

c - 查找数组中未出现两次的整数

转载 作者:太空狗 更新时间:2023-10-29 17:15:45 26 4
gpt4 key购买 nike

我正在尝试解决这个问题:在整数数组中,所有数字恰好出现两次,除了一个数字恰好出现一次。

一个简单的解决方案是对数组进行排序,然后测试是否不重复。但我正在寻找具有 O(n) 时间复杂度的更好解决方案。

最佳答案

您可以对整个数组使用“异或”运算。每对数字将相互抵消,为您留下所寻求的值(value)。

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;
}

关于c - 查找数组中未出现两次的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2168716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com