您的位置:首页 > 其它

[LeetCode] - Single Number

2013-12-16 03:09 169 查看
Description: 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?

这是整个LeetCode上面做的第一道题。没啥好说的,XOR即可。
public class Solution {
public int singleNumber(int[] A) {
int single = 0;
for(int i=0; i < A.length; i++) {
single ^= A[i];
}
return single;
}
}


http://stackoverflow.com/questions/1089987/given-an-array-of-numbers-except-for-one-number-all-the-others-occur-twice-gi

Assuming you can 
XOR
 the
numbers, that is the key here, I believe, because of the following properties:

XOR
 is
commutative and associative (so the order in which it's done is irrelevant).

a number 
XOR
ed
with itself will always be zero.

zero 
XOR
ed
with a number will be that number.

So, if you simply 
XOR
 all
the values together, all of the ones that occur twice will cancel each other out (giving 0) and the one remaining number (
n
)
will 
XOR
 with
that result (0) to give 
n
.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: