leetcode 338. Counting Bits

来源:leetcode 338. Counting Bits

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.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

下面代码运行到8时报runtime error,目测是时间复杂度的问题,需要换一种算法,不能暴力破解,明天再继续来解,加油~~~

int* countBits(int num, int* returnSize) {
    *returnSize=num+1;
    int*arr=(int*)malloc(num+1);
    int i,j;
    for(i=0;i<num+1;i++){
		arr[i]=0;
        j=i;
        while(j!=0){
            if(j%2==1)
                arr[i]++;
            j=j/2;
        }
    }
    return arr;
}


有第二种方法,但依旧没通过,还是报runtime error的错误,下次再来看这题了~

参考:LeetCode — 338. Counting Bits

思路:举例子说明:

1、最低位为0,加1之后,1的个数直接加1;

2、(i-1)次低位和最低位为01,加1之后为i,而这两低位变为10,i&(i-1)之后直接将有进位的进行了屏蔽;

3、(i-1)最后3位为011,加1之后为i,最低三位变为100,i&(i-1)之后直接将有进位的进行了屏蔽,而arr[i&(i-1)]+1即为所求值,其中+1为进位的最高位的补偿

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* countBits(int num, int* returnSize) {
    *returnSize=num+1;
    int*arr=(int*)malloc(num+1);
    arr[0]=0;
    int i;
    for(i=1;i<num+1;i++){
		arr[i]=arr[i&(i-1)]+1;
    }
    return arr;
}

在stackoverflow上提出了这个问题,原来是malloc的用法问题,一段时间不写c什么都忘了。malloc返回void*的指针,void*可强制转换为任意指针类型。

例如:

int*arr=(int*)malloc(sizeof(int)*(num+1));

表示为arr分配num+1字节的空间,然后强制转换为(int*)类型的指针

把上面的两种代码中分配空间代码改为上面这句就都可以通过了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值