题目描述
338. Counting Bits
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5,you should return[0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run time O(nsizeof(integer))*. But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Hint:
You should make use of what you have produced already.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?
解法一
解法一的PK.png我的第一个方法,达到n的复杂度。但速度慢=。=
112ms
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans ;
ans.push_back(0);//奠定第一个值
if(num == 0)//0的情况是,只有一个值。
return ans;
for(int i = 1, j = 0; i <= num ; i ++){ //i是当前数字的角标,j是已经进入的次方的级别
if(i >= pow(2,j + 1)) //循环次幂的增加
j++;
ans.push_back(ans.at(i - pow(2,j)) + 1); //值的确定:由之前的数值的循环推出
}
return ans;
}
};
解法二
受网友启发,发现直接根据他的一半的结果就能算出他的值。
110ms 12.98%
依然落后。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans;
ans.push_back(0);
for(int i = 1; i <= num; i++){
ans.push_back(ans.at(i / 2) + i % 2);
}
return ans;
}
};
解法三
同受网友启发,用他和他前面一个数的“与”位运算+1就能得到这个值。个人感觉这个规律找的很NB。
92ms
33.12%
中等偏下。。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans;
ans.push_back(0);
for(int i = 1; i <= num; i++){
ans.push_back(ans.at(i & (i - 1)) + 1);
}
return ans;
}
};
解法三优化:我把ans.at(i)函数变成了ans[]取值方式,结果快了1ms。。。
91ms;
51.48%.
中等。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans;
ans.push_back(0);
for(int i = 1; i <= num; i++){
ans.push_back(ans[i & (i - 1)] + 1);
}
return ans;
}
};
发现一些问题
- 相同的代码不同次提交会有不同的速度~好神奇
- 这道题,Java的速度居然优于C优于C++。。
好久没刷题了,这是Medium的第一个,小妞推荐的,一起努力!
——End——
网友评论