题目为: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改为n。
<a href="http://blog.csdn.net/kenden23/article/details/13625297">看到两种关于位运算的方法</a>:
1.
int singleNumber(int[] A, int n) {
for (int i=0; i<32; ++i) {
for (int j=0; j<A.length; ++i) {
int c = 0, d = 1 << i;
if ((A[j] & d) == 1) ++c;
if ((c % n) != 0) result |= d;
}
}
return result;
}
该方法运算复杂度粗略为32*n(O(n))次, 额外使用的内存只有两个int, 非常容易理解,而且也很易于扩展为n的情形。
解释:
1.任何int a = 2^(32) * a_32 + ... + 2^(i) * a_i + ... + 1 * a_1; (a_k = 0 or 1 (k = 1 ... 32));
2.对第i位来说,d = 1 << i 表示 2^(i) * 1, 对数组中的所有数字做循环
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
一般情况下,可讲题目中的2改为n。
<a href="http://blog.csdn.net/kenden23/article/details/13625297">看到两种关于位运算的方法</a>:
1.
int singleNumber(int[] A, int n) {
for (int i=0; i<32; ++i) {
for (int j=0; j<A.length; ++i) {
int c = 0, d = 1 << i;
if ((A[j] & d) == 1) ++c;
if ((c % n) != 0) result |= d;
}
}
return result;
}
该方法运算复杂度粗略为32*n(O(n))次, 额外使用的内存只有两个int, 非常容易理解,而且也很易于扩展为n的情形。
解释:
1.任何int a = 2^(32) * a_32 + ... + 2^(i) * a_i + ... + 1 * a_1; (a_k = 0 or 1 (k = 1 ... 32));
2.对第i位来说,d = 1 << i 表示 2^(i) * 1, 对数组中的所有数字做循环