leetcode吧 关注:1,123贴子:2,456
  • 0回复贴,共1

水题求解~Runtime Error LeetCode — 338. Counting Bits

只看楼主收藏回复

来源: https://leetcode.com/problems/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).
我的代码,输入8时,回报Runtime Error的错误,但是打印的结果是正确的:
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;
printf("%d\n",arr[i]);
}
return arr;
}


IP属地:北京1楼2016-07-02 12:08回复