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),我們發現數組呈現一定的規律,不斷重復,如下圖所示:
由此我們發現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]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 203. Re
- 下一篇: Leet Code OJ 8. Stri