Skip to content

Commit 1f661bb

Browse files
committed
add 3-5 answers
1 parent 3456800 commit 1f661bb

File tree

3 files changed

+72
-2
lines changed
  • lcof2
    • 剑指 Offer II 003. 前 n 个数字二进制中 1 的个数
    • 剑指 Offer II 004. 只出现一次的数字
    • 剑指 Offer II 005. 单词长度的最大乘积

3 files changed

+72
-2
lines changed

lcof2/剑指 Offer II 003. 前 n 个数字二进制中 1 的个数/Solution.cpp

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,17 @@ class Solution {
77
}
88
return f;
99
}
10-
};
10+
};
11+
12+
class Solution {
13+
public:
14+
vector<int> countBits(int n) {
15+
vector<int> ans;
16+
ans.push_back(0);
17+
for(int i = 1; i <= n; i++)
18+
{
19+
ans.push_back(ans[i & (i - 1)] +1);
20+
}
21+
return ans;
22+
}
23+
};

lcof2/剑指 Offer II 004. 只出现一次的数字/Solution.cpp

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,30 @@ class Solution {
1212
}
1313
return ans;
1414
}
15-
};
15+
};
16+
17+
class Solution {
18+
public:
19+
int singleNumber(vector<int>& nums) {
20+
vector<int> array(32);
21+
int ret = 0;
22+
for(int i = 0; i < nums.size(); i++)
23+
{
24+
for(int j = 0; j < 32; j++)
25+
{
26+
if(nums[i] & (1 << j))
27+
{
28+
array[j]++;
29+
}
30+
}
31+
}
32+
for(int i = 0; i < 32; i++)
33+
{
34+
if(array[i] % 3)
35+
{
36+
ret += ((array[i] % 3) << i);
37+
}
38+
}
39+
return ret;
40+
}
41+
};

lcof2/剑指 Offer II 005. 单词长度的最大乘积/Solution.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,35 @@ class Solution {
1919
}
2020
return ans;
2121
}
22+
};
23+
24+
int string_to_int(string word)
25+
{
26+
int ret = 0;
27+
for(int i = 0; i < word.size(); i++)
28+
{
29+
ret |= 1 << (word[i] - 'a');
30+
}
31+
return ret;
32+
}
33+
34+
class Solution {
35+
public:
36+
int maxProduct(vector<string>& words) {
37+
int max = 0, numa = 0, numb = 0;
38+
int i, j;
39+
for(i = 0; i < words.size() - 1; i++)
40+
{
41+
numa = string_to_int(words[i]);
42+
for(j = i + 1;j < words.size(); j++)
43+
{
44+
numb = string_to_int(words[j]);
45+
if( !(numa & numb))
46+
{
47+
max = max > words[i].size() * words[j].size() ? max : words[i].size() * words[j].size();
48+
}
49+
}
50+
}
51+
return max;
52+
}
2253
};

0 commit comments

Comments
 (0)