异或
因为题目要求O(n)时间,O(1)空间。
所以不能用“先排序后查找”的方法,hashtable的方法也不能用。
因为无法sort数组,所以我们用累积的方法,就和顺序无关。
XOR是一个方法,利用
A XOR A = 0, A XOR B XOR A = B
package Level1;
/**
* Single Number
*
* 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?
*/
public class S126 {
public static void main(String[] args) {
System.out.println();
}
// 异或
public static int singleNumber(int[] A) {
int res = 0;
for (int i : A) {
res ^= i;
}
return res;
}
}
public class Solution {
public int singleNumber(int[] A) {
int res = 0;
for (int i : A) {
res ^= i;
}
return res;
}
}

332

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



