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?
这个题目是做过的,之前跟王子讨论过2个不同的数字。其它都是两对相同的时候,想到了位运算这种巧妙的算法。
异或运算:相同为0,不同为1。把所有的数字都异或一遍,相同的数字异或就约掉了,只剩下那个不同的数字了。
(秒解)
class Solution {
public:
int singleNumber(int A[], int n) {
int result = 0;
for(int i=0;i<n;i++){
result=result^A[i];
}
return result;
}
};

本文介绍了一种高效的算法来找出数组中仅出现一次的元素,而其他所有元素均出现两次。通过使用异或运算,该算法能在线性时间内找到目标元素,并且不需要额外的内存空间。
391

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



