Title:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
题解:
对所有的元素用异或操作,如果两个元素是相同的,那么总有一次,他们会变为0,这样成对成对的消失(像玩连连看),最后就剩下唯一的元素。估计是我的算法资历较浅的缘故,初看到这个方法,觉得太精妙,很有启发。
int singleNumber(int A[], int n) {
int a = 0;
for (int i = 0; i < n; i++)
{
a ^=A[i];
}
return a;
}

本文介绍了一种高效的算法,用于从整数数组中找出只出现一次的元素。该算法利用异或运算的特点,在线性时间内完成任务,并且不使用额外内存。

3734

被折叠的 条评论
为什么被折叠?



