leetcode(338). Counting Bits

problem

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,检查里面1的个数的变化,只需看这个过程发生几次进位,

  • 如果没有进位1的个数加1,
  • 进位一次个数不变,
  • 进位两次个数减1,
  • … …
  • 进位n次个数减n-1

超过20%提交。

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        s = [0]
        ans = [0]
        for i in range(num):
            c = 0
            for i in range(len(s)):
                if s[i] == 0:
                    s[i] = 1
                    break
                else:
                    s[i] = 0
                    c += 1
            if c == len(s):
                s.append(1)
            ans.append(ans[-1]-(c-1))
        return ans

动态规划

上面的解法虽然也可以理解为动态规划算法(由小规模的问题答案推出大规模问题的答案,只不过递推方程计算量大),但是在discussion看到了更好的解法,例如把一个数二进制表示去掉最高位后1的个数+1就是原来的个数。

result[index] = result[index - offset] + 1(使用offset记录只有首位为1的数字,这样index-offset就相当于去掉首位1后的数字)
还有一种方法是f[i] = f[i >> q] + i & 1,(2地板除就相当于右移)
还有一种是ret[i] = ret[i&(i-1)] + 1;

n & (n - 1) unset the lower set bit of n in binary: XXX10000 ->
XXX00000

#超过70%
class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        res = [0]*(num+1)
        for i in range(1, num+1):
            res[i] = res[i>>1] + (i&1)
            #(i&1)要注意加括号,&优先级低于+
        return res

Python运算符优先级

总结

求解这个问题的关键就在于理解二进制表示,例如将一个整数的二进制形式去掉最高位怎么表达(i-offset),去掉最低位怎么表示(i//2),然后就可以将大数转化为小数,利用小规模问题推出大规模问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值