Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
338. 比特位计数 - 力扣(LeetCode) (leetcode-cn.com)
给你一个整数 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 <= 10^5
进阶:
很容易就能实现时间复杂度为 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗? 你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount )
二、思路分析:
看到这个题,解答思路很容易,但要是对复杂度限制后,怎么处理,还需要进一步考虑。先把显而易见的处理方式code一下。 1.遍历0到num中的数 2.对每一个数,转成二进制数组存储 3.遍历这个二进制数组,计算其中1的个数 4.将结果保存 思路很简单,接下来看怎么去优化,来达到进阶的要求。
三、AC 代码:
class Solution {
public int[] countBits(int num) {
int [] oneNumArray = new int [num + 1];
for(int i = 0;i <= num;i++){
ArrayList<Integer> bitArray = getBitArray(i);
int count = 0;
for(int bit : bitArray){
if (bit == 1){
count++;
}
oneNumArray[i] = count;
}
}
return oneNumArray;
}
public ArrayList<Integer> getBitArray(int num){
ArrayList<Integer> bitArray = new ArrayList<Integer>();
int mod = 0;
int res = 0;
while(num > 0){
mod = num % 2;
res = num / 2;
num = res;
bitArray.add(mod);
}
return bitArray;
}
}
四、总结:
本身挺简单,难的是题目要求的优化项。