Level:

  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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [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.

思路分析:

  我们可以用动态规划的思想来解决,dp[ i ],表示,i的二进制中1的个数,那么状态转移方程为dp[ i ]=dp[i>>1]+(i%2)。

代码:

public class Solution{
public int []countBits(int num){
int []dp=new int [num+1];
for(int i=0;i<=num;i++){
dp[i]=dp[i/2]+i&1;
}
return dp;
}
}

最新文章

  1. Asp.Net Mvc + ComBoost.Mvc快速开发
  2. Nibbler – 免费的网站测试和指标评分工具
  3. VB中 ByRef与ByVal区别
  4. &lt;转&gt;关闭 程序崩溃时 windows 正在检查该问题的解决方案
  5. MemSQL start[c]up Round 2 - online version C. More Reclamation(博弈)
  6. 服务器判断客户端为移动端还是PC端
  7. JavaScript高级程序设计之函数
  8. Linux基础--文件与目录管理
  9. 6款基于SVG的HTML5应用和动画
  10. mina2
  11. ZOJ3732 Graph Reconstruction Havel-Hakimi定理
  12. bug修复复盘
  13. 单链表的插入删除操作(c++实现)
  14. 蓝桥杯- 奇妙的数字-java
  15. C++ 多态的实现及原理
  16. Python爬虫第二天
  17. Linux(Deepin 15.9) - MySQL5.7 安装
  18. 在linux和windows用c++编写c接口的动态库
  19. npm run dev 报错 run `npm audit fix` to fix them, or `npm audit` for details
  20. 剑指offer【07】- 斐波那契数列(java)

热门文章

  1. UI库colorui的使用————小程序
  2. simple_pt时遇到的问题
  3. 二、SQL Server 分页
  4. spark- PySparkSQL之PySpark解析Json集合数据
  5. HDU4089/Uva1498 Activation 概率DP(好题)
  6. deepin开机进入intramfs无法正常开机
  7. Delphi Treeview 用法(概念、属性、添加编辑插入节点、定位节点、拖拽等)
  8. 箭头函数以及this指向问题
  9. netty-Selector
  10. PHP array_change_key_case() 函数