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

LeetCode 338. Counting Bits

时间:2016-11-30 02:31:27      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:tin   包含   ready   二进制   题目   复杂度   and   without   read   

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?

【题目分析】

给定一个数num,返回0 ≤ i ≤ num的所有数的二进制表示形式中包含的‘1’的个数。

【思路】

1. 时间复杂度为O(n*sizeof(integer))的方法

对于0到num中的每个数,如果这个数是奇数,则1的个数加1,然后该数除以2,直到该数为0. 代码如下:

 1 public class Solution {
 2     public int[] countBits(int num) {
 3         int[] result = new int[num+1];
 4         for(int i = 0; i <= num; i++) {
 5             int count = 0, x = i;
 6             while(x != 0) {
 7                 if(x % 2 == 1) count++;
 8                 x = x >> 1;
 9             }
10             result[i] = count;
11         }
12         return result;
13     }
14 }

2. 时间复杂度为O(N),空间复杂度为O(N)

求解过程中求出的一些结果其实可以直接用在后面求解中,可以大大节省代码时间复杂度,代码如下:

 1 public class Solution {
 2     public int[] countBits(int num) {
 3         int[] result = new int[num+1];
 4         for(int i = 1; i <= num; i++) {
 5             if(i % 2 == 1) {
 6                 result[i] = result[i>>1] + 1;
 7             } else {
 8                 result[i] = result[i>>1];
 9             }
10         }
11         return result;
12     }
13 }

 

LeetCode 338. Counting Bits

标签:tin   包含   ready   二进制   题目   复杂度   and   without   read   

原文地址:http://www.cnblogs.com/liujinhong/p/6115831.html

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