LN : leetcode 338 Counting Bits
2024-08-23 19:58:23
lc 338 Counting Bits
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.
规律公式 Accepted
题干中提示可以利用时间复杂度仅为O(n)的方法来做,说明一定存在着某种规律,不需要把每个数进行除二取模累加这样死做。
经过分析,可以轻松地得知一个数i,它的二进制表示含有1的个数一定等于它除去倒数第一位之外剩余1的个数再加上最后一位是否为1。所以,可易得递推式:ans[i] = ans[i/2] + i%2
,为了使得程序运行得更快,我们可以等价地用位运算去替代上式:ans[i] = ans[i >> 1] + (i & 1)
。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num+1, 0);
for (int i = 1; i <= num; i++) ans[i] = ans[i >> 1] + (i & 1);
return ans;
}
};
最新文章
- 网络IO之阻塞、非阻塞、同步、异步总结
- Andriod如何更改应用程序小图标
- 夺命雷公狗-----React---19--表单的值的修改
- UNITY5以后怎么改GUI文字
- 解决ng界面长表达式(ui-set)
- 关于cin,getchar(),scanf()的注意事项(转)
- 客户端用httpurlconnection来进行http连接的
- ANDROID_MARS学习笔记_S01_010日期时间控件
- linux文件权限详解
- Maven导入eclipse缺少web-resources目录
- php通过token验证表单重复提交
- BZOJ 3731 3731: Gty的超级妹子树 [树上size分块 !]
- TSQL:判定一段数组连续的数字段有多少的方案
- java 的序列化和反序列化的问题
- WPF 小小案列(同步异步)
- EntityFramework(1)基础概念与Database First
- 福州大学软件工程1816 | W班 第10次作业[个人作业——软件产品案例分析]
- Java如何判断文件或者文件夹是否在?不存在如何创建?
- z-tree学习笔记
- bzoj3514(主席树+lct)