LeetCode——338. Counting Bits

题型:二进制c++

题目:数组

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].ui

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.

翻译:code

给一个数字num,输出0到num间每一个数字的二进制的1的个数it

下面的时间O(n)和空间O(n)的优化要求io

 

遍历可基本解决。function

既然要到O(n),说明最后成型的数组是有规律的class

一开始的思路,因为每一个2的倍数的数加上自身都是乘2,即1往左一位,那么2^(n-1)到2^n之间的数前一半就是2^(n-2)到2^(n-1)之间的数,后一半就是2^(n-2)到2^(n-1)之间的数加1,0-7的二进制以下

0

1

10    11

100   101   111

1000 1001 1011 1100 1101 1111

则1的数量为:

0

1

1    2

1    2    2    3

1    2    2    3    2    3    3    4

因此就想着每次循环把前面的一组扩一倍而后均加1再拼到ans里

明显费时费力

这里须要细致观察,对于二进制来讲,偶数最后一位均是0,奇数均是1,因此偶数右移一位(即除以2)1的数量不变,奇数右移一位1的数量减一,以此递推的方式获取整个数组,即实现了双O(n)

代码:

class Solution(object):     def countBits(self, num):         """         :type num: int         :rtype: List[int]         """         ans = [0] * (num + 1)         for i in range(1,num + 1):             if i%2:                 ans[i] = ans[(i-1)/2] + 1             else:                 ans[i] = ans[i/2]         return ans

相关文章
相关标签/搜索