leetcode 338. Counting Bits ( Python )

565 阅读21分钟

描述

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 1:

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

Example 2:

Input: 5
Output: [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 的个数
00
11
21
32
41
52
62
73
81

通过观察可以发现其中的规律,在 2**(n) 到 2**(n+1) 之间的数字的二进制中所包含的 1 的个数分别是 0 到 2**(n) 之间数字的二进制中所包含的 1 的个数加 1。时间复杂度为 O(N),空间复杂度为 O(N)。

解答

class Solution(object):
def countBits(self, num):
    """
    :type num: int
    :rtype: List[int]
    """
    result = [0]*(num+1)
    if num==0:
        return result
    result[0] = 0
    result[1] = 1
    i = 2
    r = 2
    while i < num+1:
        if i < 2**r:
            result[i] = result[i-2**(r-1)]+1
        else:
            r+=1
            result[i] = result[i-2**(r-1)]+1
        i+=1 
    return result				

运行结果

Runtime: 68 ms, faster than 80.85% of Python online submissions for Counting Bits.
Memory Usage: 13.8 MB, less than 89.59% of Python online submissions for Counting Bits.

每日格言:逆境是达到真理的一条通路。

请作者吃薯条 支付宝

支付宝

微信

微信