LeetCode解题报告 338. Counting Bits [medium]
2016-10-21 13:28
495 查看
题目描述
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 andreturn them as an array.
Example:
For
num = 5you 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.
Hint:
You should make use of what you have produced already.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?
解题思路
题目意思就是将从0到给定的num的所有数字进行二进制表示后,计算每一个数字的二进制表示有多少个1,并输出成一个数组。同时提示不能用最无脑的办法算,要求O(n)的时间和空间复杂度。在 hint提示中,有说划分成[2,3],[4,7][8,15]来找规律,列出表格如下:
可以看到,个数在上述三个区间内分别是12,1223,12232334。
比较容易发现奇数数字1的个数都是之前一个偶数数字1的个数加一,那么再继续寻找偶数数字和之前的数字有什么关系,题目中也提示使用之前已经计算出来的数字。
在二进制的最后一位加一个0,就相当于把这个数字乘2倍,类似十进制的末位加一个0,就是把这个数字乘10倍一样。
所以说,某个偶数数字和它的1/2大小的数字的二进制形式上就是末位多了一个0,那么1的个数是一样的。如6和3,14和7等。因此,用n/2的‘1’个数的结果来表示n的结果。
时间复杂度为O(n)
代码如下:
class Solution { public: vector<int> countBits(int num) { vector<int>result(num+1,0); for (int i=1; i<=num; i++) { if (i%2==0) { result[i]=result[i/2]; } else{ result[i]=result[i-1]+1; } } return result; } };
Run Time | Language | ||
---|---|---|---|
27 minutes ago | Counting Bits | Accepted | 63 ms |
相关文章推荐
- [Leetcode] 338. Counting Bits 解题报告
- leetcode解题报告:338. Counting Bits
- [leetcode] 338. Counting Bits 解题报告
- 【LeetCode】229.Majority Element II(Medium)解题报告
- 【LeetCode】623.Add One Row to Tree(Medium)解题报告
- LeetCode解题报告 343. Integer Break [medium]
- LeetCode解题报告 108. Convert Sorted Array to Binary Search Tree [medium]
- 【LeetCode】102.Binary Tree Level Order Traversal(Medium)解题报告
- 【LeetCode】156.Binary Tree Upside Down(Medium)(加锁题)解题报告
- LeetCode解题报告 406. Queue Reconstruction by Height [medium]
- LeetCode解题报告 241. Different Ways to Add Parentheses [medium]
- 【LeetCode】6.ZigZag Conversion(Medium)解题报告
- LeetCode解题报告 377. Combination Sum IV [medium]
- 【LeetCode】103. Binary Tree Zigzag Level Order Traversal(Medium)解题报告
- 【LeetCode】199.Binary Tree Right Side View(Medium)解题报告
- 【LeetCode】513.Find Bottom Left Tree Value(Medium)解题报告
- 【LeetCode】449.Serialize and Deserialize BST(Medium)解题报告
- 【LeetCode】274.H-Index(Medium)解题报告
- leetCode 338. Counting Bits | Dynamic Programming | Medium
- 【LeetCode】320.Generalized Abbreviation(Medium)解题报告