Q1 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?
Solution 1:
这是leetcode提交成功率最高的也是最简单的一道题。最直观的作法,不考虑其对without using extra memory的限制,我们可以用一边遍历数组一边将遍历过的数字存储下来。如果这个数字之前已经遍历过了,就将他移除。这样,遍历完一遍后,剩下的一个元素,就是只出现过一次的元素了。
这样的数据结构,我们可以使用HashSet(或者HashMap)来存储遍历过的元素。如果这个元素之前出现过,就把他从set中删除。最后返回剩下的唯一的元素。
public int singleNumber(int[] A) {
if (A == null || A.length == 0) return -1;
HashSet<Integer> set = new HashSet<Integer>();
for (int i=0; i<A.length; i++) {
if (set.contains(A[i])) { set.remove(A[i]); }
else {
set.add(A[i]);
}
}
return (Integer)set.toArray()[0];
}
这样的时间复杂度是O(n),空间复杂度同样是O(n)。并且不符合without extra memory的要求。
Solution 2:
当看到两个相同的数字时,应该反应到,他们的异或(XOR, exclusive or, ^) 值为0。
x ^ x = 0, x ^ 0 = x
这样就提供了第二个解法,使用XOR计算所有的元素。出现两次的数字将XOR为0,这样只出现一次的数字就是所有元素XOR后的结果。
public int singleNumber(int[] A) {
if (A == null || A.length == 0) { return -1; }
int result = A[0];
for (int i=1; i<A.length; i++) {
result ^= A[i];
}
return result;
}
这两种方法都能通过leetcode的检测,但显然第二种才是符合要求的。