Single Number II
Total Accepted: 44725 Total Submissions: 128964
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
這個題目是,給定一個序列,所有的數字都出現三次,只有一個出現一次,找出這個數字。 如果是出現兩次的話,我們可以使用異或,異或兩次就是0了,然後剩餘的就是那個單獨的數字。
如果是出現三次的話,我們可以這樣實現:我們用一個32容量的數組儲存當前位置,bit1出現的次數。最後的時候我們把每個次數模3,這樣出現3次的就被模爲0了。
例如:
3組數字
1 0 0
0 1 0
1 0 0
1 0 0
把所有1加起來,運算的結果是
3 1 0
我們把各位模3結果就是0 1 0即是,單獨的數字。
最後把這個數字轉換成數字即可,但是需要注意,如果最高位是1的話,也就是負數,需要取反再加一。
class Solution {
public:
int singleNumber(int A[], int n) {
vector<int> bitMod3(32, 0);
int result = 0;
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < 32; ++j)
{
if(A[i] >> j & 1 == 1)
bitMod3[j]++;
}
}
for_each(bitMod3.begin(), bitMod3.end(), [](int &x)
{
x %= 3;
});
for(int i = 0; i < 32; ++i)
{
if(bitMod3[i] ^ bitMod3[31]) //如果是負數各位取反
result += pow(2, i);
}
if(bitMod3[31])
{
++result;
result = -result;
}
return result;
}
};