338.Counting Bits
Given an integer n
, return an array ans
of length n + 1
such that for each i
(0 <= i <= n
), ans[i]
is the number of 1
‘s in the binary representation of i
.
Example 1:
1 2 3 4 5 6
| Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 1 --> 1 2 --> 10
|
Example 2:
1 2 3 4 5 6 7 8 9
| Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101
|
Brian Kernighan 算法:
时间复杂度:O(nlogn)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int countOnes(int x) { int ones = 0; while (x > 0) { x &= (x - 1); ones++; } return ones; }
vector<int> countBits(int n) { vector<int> bits(n + 1); for (int i = 0; i <= n; i++) { bits[i] = countOnes(i); } return bits; } };
|
动态规划:
时间复杂度:O(n)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: vector<int> countBits(int n) { vector<int> bits(n + 1); int highBit = 0; for (int i = 1; i <= n; i++) { if ((i & (i - 1)) == 0) { highBit = i; } bits[i] = bits[i - highBit] + 1; } return bits; } };
|
1 2 3 4 5 6 7 8 9 10
| class Solution { public: vector<int> countBits(int n) { vector<int> bits(n + 1); for (int i = 1; i <= n; i++) { bits[i] = bits[i >> 1] + (i & 1); } return bits; } };
|
1 2 3 4 5 6 7 8 9 10
| class Solution { public: vector<int> countBits(int n) { vector<int> bits(n + 1); for (int i = 1; i <= n; i++) { bits[i] = bits[i & (i - 1)] + 1; } return bits; } };
|