leetcode 338. Counting Bits

发布时间:2019-06-29 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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.

思路和代码

这里除了暴力的计算每个数字中含有多少个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 &amp; (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;
    }

leetcode 338. Counting Bits


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

脚本宝典总结

以上是脚本宝典为你收集整理的leetcode 338. Counting Bits全部内容,希望文章能够帮你解决leetcode 338. Counting Bits所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。