美文网首页
Leetcode- Counting Bits

Leetcode- Counting Bits

作者: Juliiii | 来源:发表于2017-12-07 20:09 被阅读0次

Description

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.

Explain

这道题最朴素的做法就是遍历0 - num 的数,然后进行位右移统计1的个数。但是这里要求用时间复杂度是O(n),那么只能用别的方法去做了。仔细观察,可以发现,偶数的1的个数跟它除以2的结果的个数是一样的,因为该数本就是由另一个数 乘以 2得到,相当于左移了一位,奇数就是该数除以2的结果的1的个数 + 1。根据这个规律,就可以以时间复杂度为O(n)的算法解决这道题

Code

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> res;
        for (int i = 0; i <= num; i++) {
            if (i == 0) res.push_back(0);
            if (i == 1 || i == 2) res.push_back(1);
            if (i == 3) res.push_back(2);
            if (i > 3) {
                res.push_back(i % 2 == 0 ? res[i / 2] : res[i / 2] + 1);
            }
        }
        return res;
    }
};

相关文章

网友评论

      本文标题:Leetcode- Counting Bits

      本文链接:https://www.haomeiwen.com/subject/tzvjixtx.html