【leetcode】338. Counting Bits

来源:互联网 发布:高中数学算法初步教案 编辑:程序博客网 时间:2024/06/05 01:53

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.

这道题的要求时间和空间,其实它是有规律的,后面的和前面的相关。

javascript版本
Your runtime beats 69.46% of javascriptsubmissions

/** * @param {number} num * @return {number[]} */var countBits = function(num) {    var final_nums = [0];    var i=1;    var a=1;    for(var i=1;i<num+1;i++){        if(i%a==0){            a=i;        }        final_nums.push(final_nums[i-a]+1);    }    return final_nums;};

Your runtime beats 95.81% of javascriptsubmissions.

/** * @param {number} num * @return {number[]} */var countBits = function(num) {    var res = [0,1];    if(num === 0) return [0];    if(num===1){        return res;    }    var cc = 1;    for(var i=2;i<=num;i++){        if(i%cc === 0){            cc = cc*2;         }        res.push(res[i-cc]+1);    }    return res;};

You are here!
Your runtime beats 98.80% of javascriptsubmissions.

/** * @param {number} num * @return {number[]} */var countBits = function(num) {    var res = [0];    if(num === 0) return res;    var cc = 1;    for(var i=1;i<=num;i++){        if(i%cc === 0){            cc = i;         }        res.push(res[i-cc]+1);    }    return res;};
0 0