资讯专栏INFORMATION COLUMN

leetcode 338. Counting Bits

ShevaKuilin / 2837人阅读

摘要:题目要求思路和代码这里除了暴力的计算每个数字中含有多少个,我们可以使用动态规划的方法来计算中有几个。还有一种等价的思路是第位的的个数或是加上位构成的数字的的个数。

题目要求
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.
思路和代码

这里除了暴力的计算每个数字中含有多少个1,我们可以使用动态规划的方法来计算i中有几个1。假设我们已经知道前i-1个数字分别有多少个1,而且i中含有k个数字,那么其实很容易的想到,i中1的个数等于前k-1位构成的数字的1的个数,加上第k位1的个数,即1或是0。还有一种等价的思路是第0位的1的个数(0或是1)加上1~k位构成的数字的1的个数。

    public int[] countBits(int num) {
          int[] ans = new int[num + 1];
          for (int i = 1; i <= num; ++i)
            ans[i] = ans[i & (i - 1)] + 1;
          return ans;
      }
    public int[] countBits(int num) {
        int[] res = new int[num+1];
        int cur = 1;
        while(cur <= num){
            res[cur] = 1;
            cur <<= 1;
        }
        
        cur = 1;
        for(int i = 1 ; i<=num ; i++){
            if(res[i] > 0){
                cur = i;
            }else{
                res[i] = res[i-cur] + 1;
            }
        }
        return res;
    }


想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71009.html

相关文章

  • [LeetCode] Counting Bits

    Problem Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1s in their binary representation and return them as an array. Example For num = 5...

    cyixlq 评论0 收藏0
  • 大厂算法面试之leetcode精讲9.位运算

    摘要:空间复杂度方法是否为最大的幂的约数思路最大的的幂为,判断是否是的约数即可。复杂度时间复杂度,一个整数统计二进制的复杂度,最坏的情况下是。 大厂算法面试之leetcode精讲9.位运算视频教程(高效学习):点击学习目录:1.开篇介绍2.时间空间复杂度3.动态规划4.贪心5.二分查找6.深度优先&广度优先7.双指针...

    番茄西红柿 评论0 收藏2637
  • LeetCode[191] Number of 1 Bits

    摘要:依次移位复杂度思路依次移动位数进行计算。代码利用性质复杂度,思路代码 LeetCode[191] Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Fo...

    Scliang 评论0 收藏0
  • [LeetCode] 191. Number of 1 Bits

    Problem Number of 1 BitsWrite a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Example For example, the 32-bit integer 11 has bina...

    gitmilk 评论0 收藏0
  • [Leetcode] Reverse Bits 反转位

    摘要:移位法复杂度时间空间思路最简单的做法,原数不断右移取出最低位,赋给新数的最低位后新数再不断左移。代码分段相或法复杂度时间空间思路标准的源码。更好的优化方法是将其按照分成段存储,节省空间。 Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (r...

    notebin 评论0 收藏0

发表评论

0条评论

ShevaKuilin

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<