(leetcode) 338. Counting Bits
来源:互联网 发布:mac office软件破解版 编辑:程序博客网 时间:2024/04/26 00:32
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.
思路:后面的结果充分利用前面的结果,i的1的个数可以这样计算,将i右移一位,如果判断i被移掉的那一位是不是1,所以nums[i]=nums[i>>1]+i&1;根据上面这个递推式,就能ac了,时间复杂度是o(n),空间复杂度是0
代码如下(已通过leetcode)
public class Solution {
public int[] countBits(int num) {
int[] res=new int[num+1];
res[0]=0;
for(int i=1;i<=num;i++)
res[i]=res[i>>1]+(i&1);
return res;
}
}
public int[] countBits(int num) {
int[] res=new int[num+1];
res[0]=0;
for(int i=1;i<=num;i++)
res[i]=res[i>>1]+(i&1);
return res;
}
}
0 0
- [leetcode] 338. Counting Bits
- leetcode 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- (leetcode) 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode-338. Counting Bits
- leetcode-338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- 写一个函数返回参数二进制中 1 的个数
- Linux访问U盘 移动硬盘数据
- POSIX 线程编程小结
- MFC之picture控件滚动条的实现
- 快速排序递归与非递归
- (leetcode) 338. Counting Bits
- 【数字智能三篇】之一: 一页纸说清楚“什么是大数据”
- LeetCode 18 4Sum
- 数组的倒叙输出 (排列)
- IGreen爱绿项目APP和智能设备 v1.0(测试版)
- CentOS下LAMP网站架构之Apache性能调优篇
- 【数字智能三篇】之二: 一页纸说清楚“什么是推荐系统?”
- 文件的读写与访问
- poj-2528-线段树离散化区间