leetcode || 137、Single Number II
來源:程序員人生 發(fā)布時間:2015-06-01 08:47:27 閱讀次數(shù):3968次
problem:
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?
Hide Tags
Bit Manipulation
題意:1個數(shù)組中,只有1個元素出現(xiàn)1次,其他元素出現(xiàn)K次,(k為奇數(shù)3)
thinking:
(1)這道題適用于出現(xiàn)奇次的情形,解法是:對數(shù)組所有數(shù)的每位出現(xiàn)1的次數(shù)進(jìn)行統(tǒng)計,對K取余后,就為待求數(shù)在該位的位數(shù)(0或1),
再將2進(jìn)制轉(zhuǎn)換為10進(jìn)制便可
(2)這道題我假定int為32位,有些機器不是32位。
code:
class Solution {
public:
int singleNumber(vector<int>& nums) {
string s;
int a=0x0001;
int count=0;
for(int i=0;i<32;i++)
{
for(int j=0;j<nums.size();j++)
{
if((nums[j]&a)!=0)
count++;
}
s.push_back('0'+count%3);
a=a<<1;
count=0;
}
return reverse_string_to_int(s);
}
protected:
int reverse_string_to_int(string s)
{
int a=1;
int ret=0;
for(int i=0;i<s.size();i++)
{
ret+=(s.at(i)-'0')*a;
a*=2;
}
return ret;
}
};
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進(jìn)行捐贈