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)。

原创粉丝点击