您的位置:首页 > 娱乐 > 八卦 > 临淄最新招聘信息_网页建站需要多少钱_怎么制作链接网页_站长统计 网站统计

临淄最新招聘信息_网页建站需要多少钱_怎么制作链接网页_站长统计 网站统计

2024/10/10 1:33:09 来源:https://blog.csdn.net/UZDW_/article/details/142687275  浏览:    关键词:临淄最新招聘信息_网页建站需要多少钱_怎么制作链接网页_站长统计 网站统计
临淄最新招聘信息_网页建站需要多少钱_怎么制作链接网页_站长统计 网站统计

LeetCode 338. 比特位计数

给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例 1:
输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:
输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
提示:
0 <= n <= 105
进阶:
很容易就能实现时间复杂度为 O(n log n) 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗?
你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount )

class Solution:def countBits(self, n: int) -> List[int]:res = []for i in range(n + 1):sub_res = 0while i:sub_res += i & 1i >>= 1res.append(sub_res)return res

动态规划 对最高有效位计数

class Solution:def countBits(self, n: int) -> List[int]:if n == 0:return [0]# dp[i]表示 i 的二进制中包含1的位数# dp[i] = dp[i-2^k] + 1,k为非负整数,其中 2^k 为不大于i的最大的数dp = [0] * (n + 1)dp[1] = 1for i in range(2, n + 1):# k = math.floor(log2(i))# print(int(1.5))# print(int(1.51))# print(int(1.49))# print(int(-1.5))# print(int(-1.51))# print(int(-1.49))# print(int(1.9999999999999999))# print(int(-1.9999999999999999))dp[i] = dp[i - 2 ** math.floor(log2(i))] + 1return dp

动态规划 对最低有效位计数

class Solution:def countBits(self, n: int) -> List[int]:if n == 0:return [0]dp = [0] * (n + 1)dp[1] = 1for i in range(2, n + 1):dp[i] = dp[i >> 1] + (i & 1)return dp

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com