日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leet Code OJ 338. Counting Bits [Difficulty: Medium]

發布時間:2024/2/28 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。