zoukankan      html  css  js  c++  java
  • LeetCode 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 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.

    Hint:

      1. You should make use of what you have produced already.
      2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
      3. Or does the odd/even status of the number help you in calculating the number of 1s?

    【题目分析】

    给定一个数num,返回0 ≤ i ≤ num的所有数的二进制表示形式中包含的‘1’的个数。

    【思路】

    1. 时间复杂度为O(n*sizeof(integer))的方法

    对于0到num中的每个数,如果这个数是奇数,则1的个数加1,然后该数除以2,直到该数为0. 代码如下:

     1 public class Solution {
     2     public int[] countBits(int num) {
     3         int[] result = new int[num+1];
     4         for(int i = 0; i <= num; i++) {
     5             int count = 0, x = i;
     6             while(x != 0) {
     7                 if(x % 2 == 1) count++;
     8                 x = x >> 1;
     9             }
    10             result[i] = count;
    11         }
    12         return result;
    13     }
    14 }

    2. 时间复杂度为O(N),空间复杂度为O(N)

    求解过程中求出的一些结果其实可以直接用在后面求解中,可以大大节省代码时间复杂度,代码如下:

     1 public class Solution {
     2     public int[] countBits(int num) {
     3         int[] result = new int[num+1];
     4         for(int i = 1; i <= num; i++) {
     5             if(i % 2 == 1) {
     6                 result[i] = result[i>>1] + 1;
     7             } else {
     8                 result[i] = result[i>>1];
     9             }
    10         }
    11         return result;
    12     }
    13 }

     3.对上面的代码做进一步的优化

    1 public int[] countBits(int num) {
    2     int[] f = new int[num + 1];
    3     for (int i=1; i<=num; i++) f[i] = f[i >> 1] + (i & 1);
    4     return f;
    5 }

    java的位运算符要比算术运算符快很多

  • 相关阅读:
    如何编译完全使用静态库的可执行文件
    交叉编译jpeglib遇到的问题
    安装SDL遇到的问题
    软链接/硬链接删除事项
    alias命令使用
    Linux下学习摄像头使用
    018 字符串类型及操作
    017 示例3-天天向上的力量
    016 数字类型及操作
    015 基本数据类型
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6115831.html
Copyright © 2011-2022 走看看