338. Counting Bits

Problem description

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:

  1. 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?
  2. Space complexity should be O(n).

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

题目描述:

给定一个非负的整数num。对每一个位于0和num之间的数字(包括0和num)输出他们二进制形式中1的个数。

例子:

输入:5,返回[0,1,1,2,1,2]。

进一步思考:

  1. 非常容易想到复杂度是O(n*sizeof(integer))的解决办法。是否有O(n)或者说遍历一次的解决方法?
  2. 空间复杂度应该是O(n)

提示:

  1. 你应该使用你之前生成的结果。
  2. 把数字分成一个个区间,例如[2-3], [4-7], [8-15]。然后利用已生成的区间去计算新的区间。
  3. 或者利用奇偶性来帮助你计算1的数目。
链接:https://leetcode.com/problems/counting-bits/

结题思路:

我们用count来表示这个数组,前后存在递推关系。一个偶数是由小于它2倍的偶数乘2得到,与小于它的偶数相比,二进制形式中1的个数并没有变;一个奇数是由小于它两倍的偶数乘2、加1得到的,二进制形式中1的个数为小于它两倍的偶数1的个数+1。(n & 1) 就是用于判断需不需要加1。
递推式:count[n] = count[n >> 1] + (n & 1)
python代码如下:
class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        l = [0]
        for i in range(1, num + 1):
            l.append(l[i >> 1] + (i & 1))
        return l
运行时间248ms。


java代码如下:
public class Solution {
    public int[] countBits(int num) {
        int[] count = new int[num + 1];
		count[0] = 0;
		for(int i = 1; i < num + 1; i++){
			count[i] = count[i >> 1] + (i & 1);
		}
		return count;
    }
}
运行时间2ms。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值