Leet Code OJ 338. Counting Bits [Difficulty: Medium]
題目:
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.
翻譯:
給定一個非負整數num,對於每一個0<=i<=num的整數i。計算i的二進制表示中1的個數,返回這些個數作為一個數組。
比如。輸入num = 5 你應該返回 [0,1,1,2,1,2].
分析:
依照常規思路,非常容易得出“Java代碼2”的方案。可是這個方法的時間復雜度是O(nlogn)。
通過對數組的前64個元素進行分析(num=63),我們發現數組呈現一定的規律,不斷重復。例如以下圖所看到的:
0
1
1 2
1 2 2 3
1 2 2 3 2 3 3 4
1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5
1 2 2 3 2 3 3 4 2 3 3 4 3 4 4 5 2 3 3 4 3 4 4 5 3 4 4 5 4 5 5 6
由此我們發現0112是一個基礎元素。不斷循環重復。能夠推論:假設已知第一個元素是result[0],那麽第二第三個元素為result[0]+1,第四個元素為result[0]+2,由此獲得前4個元素result[0]~result[3]。以這4個元素為基礎。我們能夠得到
result[4]=result[0]+1,result[5]=result[1]+1…。
result[8]=result[0]+1,result[9]=result[1]+1… ,
result[12]=result[0]+2,result[13]=result[1]+2…;
以此類推能夠獲得所有的數組。
Java版代碼1:
public class Solution {
public int[] countBits(int num) {
int[] result = new int[num + 1];
int range = 1;
result[0] = 0;
boolean stop = false;
while (!stop) {
stop = fillNum(result, range);
range *= 4;
}
return result;
}
public boolean fillNum(int[] nums, int range) {
for (int i = 0; i < range; i++) {
if (range + i < nums.length) {
nums[range + i] = nums[i] + 1;
} else {
return true;
}
if (2 * range + i < nums.length) {
nums[2 * range + i] = nums[i] + 1;
}
if (3 * range + i < nums.length) {
nums[3 * range + i] = nums[i] + 2;
}
}
return false;
}
}
Java版代碼2:
public class Solution {
public int[] countBits(int num) {
int[] result=new int[num+1];
result[0]=0;
for(int i=1;i<=num;i++){
result[i]=getCount(i);
}
return result;
}
public int getCount(int num){
int count=0;
while(num!=0){
if((num&1)==1){
count++;
}
num/=2;
}
return count;
}
}
Leet Code OJ 338. Counting Bits [Difficulty: Medium]