LeetCode——338. Counting Bits

本文介绍了一种高效计算0至给定整数范围内所有数字二进制表示中1的数量的方法。通过观察二进制位模式,提出了一种线性时间和空间复杂度的解决方案,避免使用内置函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题型:二进制

题目:

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.

翻译:

给一个数字num,输出0到num间每个数字的二进制的1的个数

下面的时间O(n)和空间O(n)的优化要求

 

遍历可基本解决。

既然要到O(n),说明最后成型的数组是有规律的

一开始的思路,由于每个2的倍数的数加上自身都是乘2,即1往左一位,那么2^(n-1)到2^n之间的数前一半就是2^(n-2)到2^(n-1)之间的数,后一半就是2^(n-2)到2^(n-1)之间的数加1,0-7的二进制如下

0

1

10    11

100   101   111

1000 1001 1011 1100 1101 1111

则1的数量为:

0

1

1    2

1    2    2    3

1    2    2    3    2    3    3    4

所以就想着每次循环把前面的一组扩一倍然后均加1再拼到ans里

明显费时费力

这里需要细致观察,对于二进制来说,偶数最后一位均是0,奇数均是1,所以偶数右移一位(即除以2)1的数量不变,奇数右移一位1的数量减一,以此递推的方式获取整个数组,即实现了双O(n)

代码:

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        ans = [0] * (num + 1)
        for i in range(1,num + 1):
            if i%2:
                ans[i] = ans[(i-1)/2] + 1
            else:
                ans[i] = ans[i/2]
        return ans

转载于:https://my.oschina.net/u/2247638/blog/872456

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值