11.leetCode338: Counting Bits
来源:互联网 发布:微信cms是啥 编辑:程序博客网 时间:2024/05/16 09:26
题目: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.
直接能想到的方法就是将每个数字转化成二进制,再分别统计出二进制中1的个数。时间复杂度为O(n*sizeof(integer)).
改进:
求解过程中求出的一些结果其实可以直接用在后面求解中,可以大大节省代码时间复杂度。
class Solution { public int[] countBits(int num) { int[] count = new int[num+1]; for(int i=0;i<=num;i++) count[i] = count[i>>1] + (i & 1); return count; }}
注意:i>>1表示将i右移一位,等于i除以2。右移一位后,将末尾移出去了,由此,其中1的个数等于i>>1中1的个数加上末位是否为1的值(i&1)。
- 11.leetCode338: Counting Bits
- leetcode338.Counting Bits
- leetcode338 Counting Bits
- LeetCode338. Counting Bits
- LeetCode338. Counting Bits
- [LeetCode338]Counting Bits
- Leetcode338. Counting Bits
- leetcode338 Counting Bits Java
- LeetCode338. Counting Bits题解
- python--leetcode338. Counting Bits
- leetcode338:Counting Bits(medium)
- LeetCode338. Counting Bits(位运算+DP)
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- RaspberryPi树莓派安装中文输入法Fcitx
- 在PHPStrom中配置PHPunit
- linux下的僵尸进程处理SIGCHLD信号
- Win10 如何以管理员身份设置开机自启程序(2)
- 根据传入的值x的不同,返回对应的y值
- 11.leetCode338: Counting Bits
- ubuntu samba出错问题排查
- <安彦>Linux的基础命令
- 从程序猿到工程师的转变
- 解决用CreateCompatibleBitmap()创建兼容位图出现的黑底问题
- iOS下JS与原生OC互相调用
- Java后台框架篇--Spring之缓存
- 了解java .lang 包,java.util包等常用包
- MapperScannerConfigurer[注入映射器]