78. Counting Bits
2016-05-22 11:24
253 查看
Counting Bits My Submissions QuestionEditorial Solution
Total Accepted: 22588 Total Submissions: 40178 Difficulty: Medium
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.
题目:统计0到num的所有对应整数的二进制位数
本身不难,你可以很直接就想到O(n∗sizeof(int))O(n*sizeof(int))的算法
但本题要求时间复杂度O(n)O(n)
所以必须要考虑用到前面的结果来求解,不然不可能
先观察下
0 | 0 0 0 0
1 | 0 0 0 1
2 | 0 0 1 0
3 | 0 0 1 1
4 | 0 1 0 0
5 | 0 1 0 1
6 | 0 1 1 0
7 | 0 1 1 1
8 | 1 1 0 0
9 | 1 1 0 1
10 | 1 1 1 0
11 | 1 1 1 1
观察可以知道,其实在2的整数次幂的时候,后面的0或者1其实前面都出现过,比如4-7中任一个数除了第三位是1,后面2位是0-3依次排列,就是利用4-7中的某数离4的距离来确定用到的是0-3的哪个数,
这样:res[i]=res[dis]+1res[i] = res[dis]+1
其中dis=i−m(m为(1<<max(res[i]),或者理解成m=2p,2p+1>=i>=2p)dis=i-m(m为(1<=i>=2^p)
Total Accepted: 22588 Total Submissions: 40178 Difficulty: Medium
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.
题目:统计0到num的所有对应整数的二进制位数
本身不难,你可以很直接就想到O(n∗sizeof(int))O(n*sizeof(int))的算法
但本题要求时间复杂度O(n)O(n)
所以必须要考虑用到前面的结果来求解,不然不可能
先观察下
0 | 0 0 0 0
1 | 0 0 0 1
2 | 0 0 1 0
3 | 0 0 1 1
4 | 0 1 0 0
5 | 0 1 0 1
6 | 0 1 1 0
7 | 0 1 1 1
8 | 1 1 0 0
9 | 1 1 0 1
10 | 1 1 1 0
11 | 1 1 1 1
观察可以知道,其实在2的整数次幂的时候,后面的0或者1其实前面都出现过,比如4-7中任一个数除了第三位是1,后面2位是0-3依次排列,就是利用4-7中的某数离4的距离来确定用到的是0-3的哪个数,
这样:res[i]=res[dis]+1res[i] = res[dis]+1
其中dis=i−m(m为(1<<max(res[i]),或者理解成m=2p,2p+1>=i>=2p)dis=i-m(m为(1<=i>=2^p)
class Solution { public: vector<int> countBits(int num) { assert(num>=0); vector<int> res(num+1); res[0]=0; if(num==0)return res; int max = 0; for(int i=1;i<=num;++i){ int dis = i-(1<<max); res[i]=res[dis]+1; if(max<res[i])max = res[i]; } return res; } };
相关文章推荐
- BSOJ: 2697 -- 【ZJOI2010】数字计数
- 教你如何剖析源码(转)
- java 页面错误转发提示页面 errorPage转跳报HTTP500内部服务器错误
- poj 3368 Frequent values 线段树
- Icinga2在centos7上安装流程
- POJ-2096 Collecting Bugs【概率dp】
- 二项式展开推广与微积分的关系
- 一个Laravel队列引发的报警
- Android下基于PCM的音频渲染
- Visual Studio 使用技巧, 功能与特性
- Delphi项目构成之单元文件PAS
- C#第八次上机
- OJ平台汇总
- Shell脚本学习笔记-运行控制
- DHCP源码分析-报文解析和封装
- HDU 4819 二维线段树
- 专题三 · 1018
- java命令行运行带外部jar
- Git入门简介
- 第十二周进度条