• LeetCode Q338 Counting Bits(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.

    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 至 num 中每个数的二进制中1的个数。

    分析

    解法一:

      暴力算法,用一个函数算出每个数的二进制中 1 的个数,但没有满足题目要求。

    解法二:

      O(n) 的算法,说明算出每一个数的答案必定和前面的有关系。

    二进制                  1的个数

    0000                        0

    0001                        1

    0010                        1

    0011                        2 

    0100                        1

    0101                        2

    0110                        2

    0111                        3

     ……                        ……

      第一种规律,n 的二进制中 1 的个数等于 n-4 的二进制中 1 的个数加一。

      如果把最后一位于前面的分开呢?

     二进制                  1的个数

     000  0                      0

     000  1                      1

     001  0                      1

     001  1                      2 

     010  0                      1

     010  1                      2

     011  0                      2

     011  1                      3

     ……                        ……

      可以发现,右移一位后的数必定比它本身小,所以之前必定算过,也就是每个数只要判断最后一位数和右移一位后的的数含有1的个数。满足题目一切条件

     1 public class Solution 
     2 {
     3     public int[] CountBits(int num) 
     4     {
     5         int[] ret=new int[num+1];
     6         ret[0]=0;
     7         for (int i=1;i<=num;i++) ret[i]=ret[i>>1]+i%2;
     8         return ret;
     9     }
    10 }
  • 相关阅读:
    Ubuntu18.04 server 双网卡,一个设置为静态IP, 一个设置为动态IP
    【转载】 Ubuntu 中开机自动执行脚本的两种方法
    Ubuntu18.04server 双网卡,开机自动设置路由并启动校园网网络认证程序(Ubuntu开机自动设置路由,开机自启动应用程序)
    mpi4py 官方使用手册
    【转转】 Huber Loss
    【转载】 MPP大规模并行处理架构详解
    并行强化学习设计的一些想法
    人工智能必备数学基础-回归方程定义
    tf.gather()、tf.gather_nd()、tf.batch_gather()、tf.where()和tf.slice()
    C# 计算时间间隔
  • 原文地址:https://www.cnblogs.com/Bita/p/5932307.html
Copyright © 2020-2023  润新知