国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Counting Bits

2019-11-06 09:23:36
字體:
來源:轉載
供稿:網友

題目地址:https://leetcode.com/PRoblems/counting-bits/?tab=Description

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.

這個題目有點意思,簡單的思考后我們很快地就能發現結果數組的下標與其對應的整數值的關系:下標對應的二進制中1的個數就是其對應的元素的數值。

那這個題目關鍵是不讓去逐位分析整數,那咋辦?

那我們隨便寫幾個,看看有啥規律:

1 bitbc[0] => 0000 => 0bc[1] => 0001 => 12 bitsbc[2] => 0010 => 0010 + 0 => 1 + bc[0];bc[3] => 0011 => 0010 + 1 => 1 + bc[1];3 bitsbc[4] => 0110 => 0100 + 00 => 1 + bc[0];bc[5] => 0101 => 0100 + 01 => 1 + bc[1];bc[6] => 0110 => 0100 + 10 => 1 + bc[2];bc[7] => 0111 => 0100 + 11 => 1 + bc[3];

看到這里貌似清晰不少了,于是有

rs[x] = rs[x & (x-1)] + 1

那么實現如下:

public class CountingBits { public static int[] countBits(int num) { int[] rs = new int[num + 1]; for (int i = 0; i <= num; i++) { rs[i] = rs[i & (i - 1)] + 1; } return rs; } public static void main(String[] args) { System.out.println(Arrays.asList(countBits(5))); return; }}

參考文獻: https://github.com/haoel/leetcode/tree/master/algorithms/cpp/countingBits


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 清河县| 山东| 英山县| 洪泽县| 玉溪市| 镇原县| 定结县| 宜州市| 太湖县| 武鸣县| 甘德县| 高安市| 南丹县| 灵宝市| 临潭县| 囊谦县| 萨嘎县| 陆丰市| 琼海市| 镇雄县| 泰和县| 化隆| 河源市| 瑞安市| 额济纳旗| 同江市| 湟源县| 绥化市| 仁寿县| 寻甸| 离岛区| 从江县| 新野县| 台北市| 台州市| 灵寿县| 沧源| 寻乌县| 阳曲县| 南充市| 永安市|