[刷题]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.
思路:
O(n*n)过于简单,不再赘述。为了实现O(n),需要观察一下。一下描述用c(n)来代表n包含二进制1的个数。
- c(0) = 0, c(1) = 1;
- c(2) = 1, c(3) = c(1) + c(2) = c(1) + 1;
- c(4) = 1, c(5) = c(1) + c(4) = c(1) + 1, c(6) = c(2) + c(4) = c(2) + 1, c(7) = c(3) + c(4) = c(3) + 1;
- ……
- c(n) = c(n-m) + 1; m是小于等于n的最大2的整次幂
1 class Solution { 2 public: 3 vector<int> countBits(int num) { 4 vector<int> vec; 5 int cur = 1; 6 int next = 2; 7 for(int i=0;i<=num;i++) { 8 if (i < 2) 9 { 10 vec.push_back(i); 11 continue; 12 } 13 if (i == next) 14 { 15 cur = next; 16 next = next << 1; 17 } 18 if (i >= cur) 19 { 20 vec.push_back(vec[i-cur]+1); 21 } 22 } 23 return vec; 24 } 25 };