leetcode-338-Counting Bits
2016-03-19 11:09
417 查看
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
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
给定num,对于每个 0<= i <=num , 计算i的2进制中1的个数。
若对每个数,进行每位的判断,时间复杂度是O(n*logn)。
可以从每个数的最低位开始分析,例如1001001 ,它的二进制1的个数等于100100 总二进制个数 + 1 。
即 f = f/2 + (f 的最低位)
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 = 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
给定num,对于每个 0<= i <=num , 计算i的2进制中1的个数。
若对每个数,进行每位的判断,时间复杂度是O(n*logn)。
可以从每个数的最低位开始分析,例如1001001 ,它的二进制1的个数等于100100 总二进制个数 + 1 。
即 f = f/2 + (f 的最低位)
class Solution { public: vector<int> countBits(int num) { vector<int> v(num + 1 , 0) ; for (int i = 1 ; i <= num ; i ++) { v[i] = v[i>>1] + i%2 ; } return v ; } };
相关文章推荐
- http异步请求
- hdu 3652 B-number
- 栈的链式存储(含源码)
- ZOJ 3620 Escape Time II(BFS)
- Android 输出XML
- 认识Ajax
- 帝国CMS开启全站搜索功能
- kettle 定时任务(使用资源库)
- sql 的一些数据优化
- 蒙特卡洛法求圆周率pi
- php webservice实现
- 第六届 蓝桥杯 第七题 手链样式 枚举 暴力 解题报告
- 上海地铁(分象限)
- 202. Happy Number
- c++ 单链表 双向链表 链表笔试题
- Android AutoLayout全新的适配方式 堪称适配终结者
- 2016年调薪谈话
- PullToRefresh使用详解(一)--构建下拉刷新的listView
- POJ 3278 Catch That Cow
- Apache和tomcat之间的区别和联系