Leetcode May Challenge - 05/28: Counting Bits(Python)

题目描述

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.
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.

例子

Example 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]

解释

给一个正整数n,返回一个列表,列表中存储从0到n的每个数的二进制表示中有多少个1。
要求空间复杂度为O(n),时间复杂度也为O(n)。

思路 动态规划

我们先来写几个二进制数字找一下规律:

0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
...

我们可以发现,把位数相同的数字视为一组,把最低位去掉,剩余的位数实际上是上一组数字的每个数字出现了两次。比如100,101,110,111,去掉最低位后变成了10,10,11,11,恰好是上一组10,11的每个数字出现两次。
继续探索,如果最低位是1,则证明该数为奇数,反之则为偶数。所以,如果是奇数,就把上一组对应位置的1的个数加1,偶数则直接拿过来存。(这里注意我们需要一个res数组去存之前的结果,最后直接返回出来。因此我们在需要前面一组的1的个数的时候不用重新计算,直接取对应位置拿出来即可)。

代码

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        if num == 0:
            return [0]
        if num == 1:
            return [0, 1]
        res = [0, 1]
        #power用来记录上一组的元素个数
        #cnt用来记录res中元素个数
        power = 1
        cnt = 2
        while cnt <= num:
            for i in range(power):
                res.append(res[power + i])
                res.append(res[power + i] + 1)
                cnt += 2
            power *= 2
        return res[:num + 1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值