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?
思路:题目要求时间复杂度为O(n),并且空间复杂度为O(1).考虑用位操作。这里我们用异或^。
异或规则:如果两个比特位相同,异或之后变为0,两个比特位不同,则异或之后为1.且a ^ b = b ^ a, a ^ 0 = a.
我们将数组中的数从头到尾异或一遍,得到的值即为所求。
C++代码实现:
class Solution {
public:
int singleNumber(int A[], int n) {
if(A == NULL || n <= 0)
return 0;
int single_num = A[0];
for(int i = 1;i < n;i++){
single_num = single_num ^ A[i];
}
return single_num;
}
};