码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Q338 Counting Bits(Medium)

时间:2016-11-05 11:27:28      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:linear   etc   without   答案   its   pop   lex   style   oss   

原题:

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.

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.

翻译:给定一个非负整数num,求出0至num中每个数的二进制中1的个数。

分析:

解法一:

  暴力算法,用一个函数算出每个数的二进制中1的个数,但没有满足题目要求。

解法二:

  O(n)的算法,说明算出每一个数的答案必定和前面的有关系。

二进制                  1的个数

0000                        0

0001                        1

0010                        1

0011                        2 

0100                        1

0101                        2

0110                        2

0111                        3

 ……                        ……

  第一种规律,n的二进制中1的个数等于n-4的二进制中1的个数加一。

  如果把最后一位于前面的分开呢?

 二进制                  1的个数

 000  0                      0

 000  1                      1

 001  0                      1

 001  1                      2 

 010  0                      1

 010  1                      2

 011  0                      2

 011  1                      3

 ……                        ……

  动态规划的思想,因为右移一位的数必定比它小,所以之前必定算过,只需要看最后一位就行了。满足题目一切条件

 1 public class Solution 
 2 {
 3     public int[] CountBits(int num) 
 4     {
 5         int[] ret=new int[num+1];
 6         ret[0]=0;
 7         for (int i=1;i<=num;i++) ret[i]=ret[i>>1]+i%2;
 8         return ret;
 9     }
10 }

LeetCode Q338 Counting Bits(Medium)

标签:linear   etc   without   答案   its   pop   lex   style   oss   

原文地址:http://www.cnblogs.com/Bita/p/5932307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!