leetcode || 137、Single Number II
來源:程序員人生 發布時間:2015-06-01 08:47:27 閱讀次數:3959次
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個數組中,只有1個元素出現1次,其他元素出現K次,(k為奇數3)
thinking:
(1)這道題適用于出現奇次的情形,解法是:對數組所有數的每位出現1的次數進行統計,對K取余后,就為待求數在該位的位數(0或1),
再將2進制轉換為10進制便可
(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;
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈