lc 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(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.
规律公式 Accepted
题干中提示可以利用时间复杂度仅为O(n)的方法来做,说明一定存在着某种规律,不需要把每个数进行除二取模累加这样死做。
经过分析,可以轻松地得知一个数i,它的二进制表示含有1的个数一定等于它除去倒数第一位之外剩余1的个数再加上最后一位是否为1。所以,可易得递推式:ans[i] = ans[i/2] + i%2
,为了使得程序运行得更快,我们可以等价地用位运算去替代上式:ans[i] = ans[i >> 1] + (i & 1)
。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num+1, 0);
for (int i = 1; i <= num; i++) ans[i] = ans[i >> 1] + (i & 1);
return ans;
}
};