題目要求找出在算法的時(shí)間復(fù)雜度為線(xiàn)性時(shí)間,且不占據(jù)額外的內(nèi)存
class Solution
{
public:
int singleNumber(int A[], int n) {
int temp = 0;
for (int i = 0; i < n; i++)
{
temp ^= A[i];
}
return temp;
}
};
下面講解算法:
該算法主要用到了位運(yùn)算中的異或運(yùn)算^,進(jìn)一步地說(shuō)是用到了異或的如下三個(gè)性質(zhì)
0^A=A (1)
A^A=0 (2)
AB=BA (3)
假設(shè)目前我們輸入的數(shù)組為1 2 3 1 3,按照算法,我們將這樣運(yùn)行程序
step 1: temp=0^1=1,即性質(zhì)1
step 2: temp=1^2
step 3: temp=123
step 4: temp=123^1,根據(jù)性質(zhì)3 該式子可以轉(zhuǎn)化為temp=1213=1123,根據(jù)性質(zhì)2和性質(zhì)1 temp=023=2^3
step 5: temp=233, 同上,式子可以轉(zhuǎn)化為 temp=2,即為所求