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?
Solution in Java:
public class Solution {
public int singleNumber(int[] A) {
int num=0;
for(int i=0; i<A.length; i++){
num = num^A[i];
}
return num;
}
}
Note: ^是按位异或符号,遵守交换律和结合律,0与任何数异或结果均为该数。注意复习逻辑运算符。
参考资料:http://help.topcoder.com/data-science/competing-in-algorithm-challenges/algorithm-tutorials/a-bit-of-fun-fun-with-bits/
本文介绍了一种线性时间复杂度的算法来找出数组中只出现一次的元素,利用按位异或操作实现,避免了额外内存的使用。

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



