问题:
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?
因为我先做的Single Number II,所以自然想到那道题的思路:由于不让用extra memory,我们保存一个32位的array,来记录array中每一个数的为1的位。由于除了一个数以外的所有数都是出现了两次,他们的对应为1的位累计之和肯定可以被2整除;而只出现一次的那个数对应的1的位,肯定不能被2整除。
代码:
class Solution {
public:
int singleNumber(int A[], int n) {
int count[32] = {0};
int result = 0;
for (int i = 0; i < 32; i ++) {
for (int j = 0; j < n; j ++) {
int num = A[j];
count[i] += (num >> i) & 1;
}
result |= ((count[i] % 2) << i);
}
return result;
}
};
经过在网上搜索,我发现了另外一个答案:使用exclusive or。XOR的特点是:如果两个operand一样(比如都是1或者都是0),那么就返回0;如果不一样,则返回1。值得注意的是,根据这个性质,0 XOR a = a for any a. 也就是说,一个数跟零进行exclusive or,结果就是那个数不变。还有就是,如果是两个相同的数进行XOR,则结果为0,因为它们的每一位都是一样的,所以每一位的结果都是0。最后,XOR满足交换律。所以我们需要做的就是:把array中所有的数一个一个XOR下去,那么由于交换律,我们可以把相同的两个数都放在一起,所以变成了0;最后只剩下0与只出现一次的那个数进行XOR,那结果就是只出现过一次的那个数。
代码:
class Solution {
public:
int singleNumber(int A[], int n) {
int result = 0;
for (int i = 0; i < n; i ++) {
result ^= A[i];
}
return result;
}
};