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