Description
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(n*sizeof(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.
Explain
這道題最樸素的做法就是遍歷0 - num 的數(shù),然后進(jìn)行位右移統(tǒng)計(jì)1的個(gè)數(shù)。但是這里要求用時(shí)間復(fù)雜度是O(n)怎爵,那么只能用別的方法去做了抵怎。仔細(xì)觀察陋率,可以發(fā)現(xiàn)佩番,偶數(shù)的1的個(gè)數(shù)跟它除以2的結(jié)果的個(gè)數(shù)是一樣的蔓挖,因?yàn)樵摂?shù)本就是由另一個(gè)數(shù) 乘以 2得到附帽,相當(dāng)于左移了一位埠戳,奇數(shù)就是該數(shù)除以2的結(jié)果的1的個(gè)數(shù) + 1。根據(jù)這個(gè)規(guī)律蕉扮,就可以以時(shí)間復(fù)雜度為O(n)的算法解決這道題
Code
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
for (int i = 0; i <= num; i++) {
if (i == 0) res.push_back(0);
if (i == 1 || i == 2) res.push_back(1);
if (i == 3) res.push_back(2);
if (i > 3) {
res.push_back(i % 2 == 0 ? res[i / 2] : res[i / 2] + 1);
}
}
return res;
}
};