当前位置: 首页 > news >正文

LeetCode 338. 比特位计数

给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。

示例 1:

输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10

提示:

0 <= n <= 105

进阶:

很容易就能实现时间复杂度为 O(n log n) 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗?
你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount )

解法一:动态规划,如3的比特位为1的位数等于将3右移一位(即1)的比特位为1的位数加上3&1:

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

此算法时间复杂度为O(n),空间复杂度为O(1)。

解法二:每个数字都计算一遍位数:

class Solution {
public:vector<int> countBits(int n) {vector<int> ans(n + 1, 0);for (int i = 1; i <= n; ++i) {int ibak = i;while (ibak) {ans[i] += ibak & 1;ibak >>= 1;}} return ans;}
};

此算法时间复杂度为O(nlgn),空间复杂度为O(1)。

解法三:使用库函数:

class Solution {
public:vector<int> countBits(int n) {vector<int> ans(n + 1, 0);for (int i = 1; i <= n; ++i) {ans[i] = __builtin_popcount(i);} return ans;}
};

此算法时间复杂度为O(nlgn),空间复杂度为O(1)。__builtin_popcount函数的时间复杂度为O(lgn)。

解法四:利用x&(x-1)的结果是x的最低的比特位从1变成0:

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

此算法时间复杂度为O(nlgn),空间复杂度为O(1)。

解法五:动态规划,最高位一定为1,x的比特位为1的计数等于去掉最高位后的数字的比特位为1的计数加上最高位的1:

class Solution {
public:vector<int> countBits(int n) {vector<int> ans(n + 1, 0);int highestBit = 0;for (int i = 1; i <= n; ++i) {// 当i是2的幂时,更新最高位if ((i & (i - 1)) == 0) {highestBit = i;}ans[i] = ans[i - highestBit] + 1;} return ans;}
};

此算法时间复杂度为O(n),空间复杂度为O(1)。

解法六:动态规划,x的比特位为1的计数等于把x的最低位的1改为0后的数的比特位为1的计数加上最低位的1:

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

此算法时间复杂度为O(n),空间复杂度为O(1)。

http://www.lryc.cn/news/11828.html

相关文章:

  • 排序评估指标——NDCG和MAP
  • [Android Studio] Android Studio Virtual Device(AVD)虚拟机的功能试用
  • kafka-3-kafka应用的核心要点和内外网访问
  • VS2017+OpenCV4.5.5 决策树-评估是否发放贷款
  • Prometheus 记录规则和警报规则
  • (API)接口测试的关键技术
  • 快速排序算法原理 Quicksort —— 图解(精讲) JAVA
  • linux环境搭建私有gitlab仓库
  • SpringSecurity授权
  • 学习 Python 之 Pygame 开发坦克大战(一)
  • 2.5|iot冯|方元-嵌入式linux系统开发入门|2.13+2.18
  • 一起Talk Android吧(第四百九十六回:自定义View实例二:环形进度条)
  • 上传图片尺寸校验
  • 【Python】缺失值处理和拉格朗日插值法(含源代码实现)
  • SpringCloudAlibaba-Sentinel
  • 【程序化天空盒】过程记录02:云扰动 边缘光 消散效果
  • 链表OJ(三) 反转链表合集
  • SQLSERVER2019安装步骤过程
  • Java模块化概述
  • Connext DDSPersistence Service持久性服务(2)
  • MongoDB
  • python 迭代器生成器
  • Iceberg基于Spark MergeInto语法实现数据的增量写入
  • JavaScript Array(数组) 对象
  • Debian如何更换apt源
  • Connext DDSPersistence Service持久性服务
  • 自抗扰控制ADRC之微分器TD
  • 链表学习之复制含随机指针的链表
  • 【人脸检测】Yolov5Face:优秀的one-stage人脸检测算法
  • 【Unity3d】Unity与Android之间通信