Leetcode 338. Counting Bits

博客围绕LeetCode上一道计算二进制中1的个数的题目展开。给出两种代码实现,分析了它们的时间和空间复杂度均为O(n)。代码一通过观察相邻整数二进制特点优化,代码二通过高位去1后计算。还提及代码二速度弱于代码一,且复杂度分析可能不精确。

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

题目

链接:https://leetcode.com/problems/counting-bits

Level: Medium

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

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

Note:

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

代码一

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> d(num+1, 0);
        d[0]=0;
        for(int i=1;i<=num;i++)
        {
            d[i] = d[i&i-1]+1;  
        }
        return d;
    }
};

思考

  • 算法时间复杂度为O(\(n\)),空间复杂度为O(\(n\) )。
  • 这里观察到相邻两个整数转化为二进制的特点。当末位为0时,加1之后,二进制中1的个数就为前一个数的结果加1。当末位为1时,再加1,那么1会往前传递,1停在二进制为0的地方。比如1011,转化为1100,而曾经为1的地方变为0。此时i&i-1的意义在于取到相同的高位。而高位右边的各位必定只有一个传递过来的1。
  • vector数组可以初始化长度和值。这样做的好处是能节省一半的内存,因为使用push_back()时,vector会扩展此时所占空间一半的长度。所以如果已知所用空间的大小,直接固定长度进行初始化vector。

代码二

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> d;
        d.push_back(0);
        for(int i=1;i<=num;i++)
        {
            int t = int(log2(i));
            int temp = pow(2,t)==i ? 1:d[i-pow(2,t)]+1;
            d.push_back(temp);
        }
        return d;
    }
};

思考

  • 算法时间复杂度为O(\(n\)),空间复杂度为O(\(n\) )。
  • 代码二是观察到高位去1后所得整数,转化为二进制中1的个数再加一,可得当前数二进制中1的个数。
  • 这里的复杂度分析应该不精确,因为不清楚log和pow的复杂度,但是想来应该和num的长度有关,note中提到的sizeof(integer)。运行出来也是代码二速度明显弱于代码一。

转载于:https://www.cnblogs.com/zuotongbin/p/10553912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值