LeetCode 338. Counting Bits
Posted Black_Knight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 338. Counting Bits相关的知识,希望对你有一定的参考价值。
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:
- You should make use of what you have produced already.
- Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
- 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的主要内容,如果未能解决你的问题,请参考以下文章