首页 > 代码库 > LeetCode 338. Counting Bits
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。