338.Counting Bits
338.Counting Bits
难度:Medium
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.
1
Example 1:
2
3
Input: 2
4
Output: [0,1,1]
5
Example 2:
6
7
Input: 5
8
Output: [0,1,1,2,1,2]
9
Follow up:
10
11
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
12
Space complexity should be O(n).
13
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Copied!
这题可以采用与78.subsets相似的方法,循环,然后判断位数。
1
class Solution {
2
public:
3
vector<int> countBits(int num) {
4
int s= log(num)/log(2);
5
if(pow(2,s) <num) s+=1;
6
int N= 1;
7
int count =1;
8
vector<int> res(num+1, 0);
9
for(int i=1;i<=num;i++)
10
{
11
int count =0;
12
for(int j=0;j<=s;j++)
13
if(i & (1<<j)) count++;
14
res[i] = count;
15
}
16
return res;
17
}
18
};
Copied!
执行用时 :152 ms, 在所有 C++ 提交中击败了8.83%的用户 内存消耗 :9.9 MB, 在所有 C++ 提交中击败了3.54%的用户
但是效率较低,可以采用动态规划的方法,对于一个数,通过该数的1/2的位数和该数末尾是否为1来确定该数的位数。
1
class Solution {
2
vector <int > counts={0,1,1,2,1};
3
public:
4
vector<int> countBits(int num) {
5
if(num <counts.size())
6
{
7
vector<int > res(counts.begin(), counts.begin()+num+1);
8
return res;
9
}
10
for(int i=counts.size(); i<=num;i++)
11
counts.push_back( counts[i/2] + i%2);
12
return counts;
13
}
14
};
Copied!
执行用时 :84 ms, 在所有 C++ 提交中击败了67.28%的用户 内存消耗 :10.8 MB, 在所有 C++ 提交中击败了5.19%的用户
Copy link