当前位置: 首页 > news >正文

LeetCode-Count 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 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.

Analysis:

0 | 0+1| 0+1 1+1| 0+1 1+1 1+1 2+1 |..........

0 | 1    | 1       2  | 1      2    2     3     |................

Solution:

public class Solution {
    public int[] countBits(int num) {
        int[] res = new int[num + 1];

        res[0] = 0;
        int nextNum = 1;
        int nextCount = 1;
        while (nextNum <= num) {
            for (int i = 0; i < nextCount && nextNum <= num; i++) {
                res[nextNum++] = res[i] + 1;
            }
            nextCount *= 2;
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/lishiblog/p/5832068.html

相关文章:

  • Java中对HashMap的深度分析与比较
  • java 线程小结
  • JAVA中精确计算金额BigDecimal
  • java并发编程实践笔记
  • 第四章 進程調度
  • volatile原理与技巧
  • java I/O的基本使用
  • java多线程中的join方法详解
  • java多线程总结
  • PHP 图片处理工具类(添加水印与生成缩略图)
  • MyEclipse 8.0 GA 搭建 Struts2 + Spring2 + Hibernate3 (测试)
  • MyEclipse从数据库反向生成实体类之Hibernate方式
  • 城市选择案例
  • 《深入浅出 Java Concurrency》——原子操作
  • 第18章 认识系统服务(daemons)
  • “大数据应用场景”之隔壁老王(连载四)
  • 【RocksDB】TransactionDB源码分析
  • 2017前端实习生面试总结
  • android图片蒙层
  • Apache的基本使用
  • JavaScript 基础知识 - 入门篇(一)
  • JavaScript 事件——“事件类型”中“HTML5事件”的注意要点
  • js中forEach回调同异步问题
  • Leetcode 27 Remove Element
  • ReactNative开发常用的三方模块
  • 程序员该如何有效的找工作?
  • 服务器从安装到部署全过程(二)
  • 基于Javascript, Springboot的管理系统报表查询页面代码设计
  • 巧用 TypeScript (一)
  • 时间复杂度与空间复杂度分析
  • 实习面试笔记
  • 微信开放平台全网发布【失败】的几点排查方法
  • 浅谈sql中的in与not in,exists与not exists的区别
  • # 日期待t_最值得等的SUV奥迪Q9:空间比MPV还大,或搭4.0T,香
  • ###项目技术发展史
  • (0)Nginx 功能特性
  • (3)(3.2) MAVLink2数据包签名(安全)
  • (42)STM32——LCD显示屏实验笔记
  • (done) NLP “bag-of-words“ 方法 (带有二元分类和多元分类两个例子)词袋模型、BoW
  • (Redis使用系列) Springboot 在redis中使用BloomFilter布隆过滤器机制 六
  • (ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)讲解
  • (超简单)构建高可用网络应用:使用Nginx进行负载均衡与健康检查
  • (第9篇)大数据的的超级应用——数据挖掘-推荐系统
  • (分布式缓存)Redis分片集群
  • (附源码)spring boot车辆管理系统 毕业设计 031034
  • (三)uboot源码分析
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (四)Linux Shell编程——输入输出重定向
  • (淘宝无限适配)手机端rem布局详解(转载非原创)
  • (一)搭建springboot+vue前后端分离项目--前端vue搭建
  • (转)【Hibernate总结系列】使用举例
  • (转载)PyTorch代码规范最佳实践和样式指南
  • (轉貼) UML中文FAQ (OO) (UML)
  • .net实现头像缩放截取功能 -----转载自accp教程网
  • .ui文件相关