LeetCode解题报告 338. Counting Bits [medium]

来源:互联网 发布:原生js添加子节点 编辑:程序博客网 时间:2024/05/27 09:45

题目描述

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?

解题思路

题目意思就是将从0到给定的num的所有数字进行二进制表示后,计算每一个数字的二进制表示有多少个1,并输出成一个数组。同时提示不能用最无脑的办法算,要求O(n)的时间和空间复杂度。
在 hint提示中,有说划分成[2,3],[4,7][8,15]来找规律,列出表格如下:



可以看到,个数在上述三个区间内分别是12,1223,12232334。
比较容易发现奇数数字1的个数都是之前一个偶数数字1的个数加一,那么再继续寻找偶数数字和之前的数字有什么关系,题目中也提示使用之前已经计算出来的数字。
在二进制的最后一位加一个0,就相当于把这个数字乘2倍,类似十进制的末位加一个0,就是把这个数字乘10倍一样。
所以说,某个偶数数字和它的1/2大小的数字的二进制形式上就是末位多了一个0,那么1的个数是一样的。如6和3,14和7等。因此,用n/2的‘1’个数的结果来表示n的结果。

时间复杂度为O(n)

代码如下:
class Solution {public:    vector<int> countBits(int num) {        vector<int>result(num+1,0);        for (int i=1; i<=num; i++) {            if (i%2==0) {                result[i]=result[i/2];            }            else{                result[i]=result[i-1]+1;            }        }        return result;    }};

Run TimeLanguage27 minutes agoCounting BitsAccepted63 ms运行时间>80%多的其他cpp

0 0
原创粉丝点击