题目要求找出在算法的时间复杂度为线性时间,且不占据额外的内存
class Solution
{
public:
int singleNumber(int A[], int n) {
int temp = 0;
for (int i = 0; i < n; i++)
{
temp ^= A[i];
}
return temp;
}
};
下面讲解算法:
该算法主要用到了位运算中的异或运算^,进一步地说是用到了异或的如下三个性质
0^A=A (1)
A^A=0 (2)
AB=BA (3)
假设目前我们输入的数组为1 2 3 1 3,按照算法,我们将这样运行程序
step 1: temp=0^1=1,即性质1
step 2: temp=1^2
step 3: temp=123
step 4: temp=123^1,根据性质3 该式子可以转化为temp=1213=1123,根据性质2和性质1 temp=023=2^3
step 5: temp=233, 同上,式子可以转化为 temp=2,即为所求