摘要:題目要求思路和代碼這里除了暴力的計算每個數(shù)字中含有多少個,我們可以使用動態(tài)規(guī)劃的方法來計算中有幾個。還有一種等價的思路是第位的的個數(shù)或是加上位構(gòu)成的數(shù)字的的個數(shù)。
題目要求
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.思路和代碼
這里除了暴力的計算每個數(shù)字中含有多少個1,我們可以使用動態(tài)規(guī)劃的方法來計算i中有幾個1。假設(shè)我們已經(jīng)知道前i-1個數(shù)字分別有多少個1,而且i中含有k個數(shù)字,那么其實很容易的想到,i中1的個數(shù)等于前k-1位構(gòu)成的數(shù)字的1的個數(shù),加上第k位1的個數(shù),即1或是0。還有一種等價的思路是第0位的1的個數(shù)(0或是1)加上1~k位構(gòu)成的數(shù)字的1的個數(shù)。
public int[] countBits(int num) { int[] ans = new int[num + 1]; for (int i = 1; i <= num; ++i) ans[i] = ans[i & (i - 1)] + 1; return ans; }
public int[] countBits(int num) { int[] res = new int[num+1]; int cur = 1; while(cur <= num){ res[cur] = 1; cur <<= 1; } cur = 1; for(int i = 1 ; i<=num ; i++){ if(res[i] > 0){ cur = i; }else{ res[i] = res[i-cur] + 1; } } return res; }
想要了解更多開發(fā)技術(shù),面試教程以及互聯(lián)網(wǎng)公司內(nèi)推,歡迎關(guān)注我的微信公眾號!將會不定期的發(fā)放福利哦~
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/71009.html
Problem Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1s in their binary representation and return them as an array. Example For num = 5...
摘要:空間復(fù)雜度方法是否為最大的冪的約數(shù)思路最大的的冪為,判斷是否是的約數(shù)即可。復(fù)雜度時間復(fù)雜度,一個整數(shù)統(tǒng)計二進制的復(fù)雜度,最壞的情況下是。 大廠算法面試之leetcode精講9.位運算視頻教程(高效學(xué)習(xí)):點擊學(xué)習(xí)目錄:1.開篇介紹2.時間空間復(fù)雜度3.動態(tài)規(guī)劃4.貪心5.二分查找6.深度優(yōu)先&廣度優(yōu)先7.雙指針...
摘要:依次移位復(fù)雜度思路依次移動位數(shù)進行計算。代碼利用性質(zhì)復(fù)雜度,思路代碼 LeetCode[191] Number of 1 Bits Write a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Fo...
Problem Number of 1 BitsWrite a function that takes an unsigned integer and returns the number of ’1 bits it has (also known as the Hamming weight). Example For example, the 32-bit integer 11 has bina...
摘要:移位法復(fù)雜度時間空間思路最簡單的做法,原數(shù)不斷右移取出最低位,賦給新數(shù)的最低位后新數(shù)再不斷左移。代碼分段相或法復(fù)雜度時間空間思路標(biāo)準(zhǔn)的源碼。更好的優(yōu)化方法是將其按照分成段存儲,節(jié)省空間。 Reverse Bits Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (r...
閱讀 881·2021-11-15 11:37
閱讀 3619·2021-11-11 16:55
閱讀 3284·2021-11-11 11:01
閱讀 1008·2019-08-30 15:43
閱讀 2755·2019-08-30 14:12
閱讀 695·2019-08-30 12:58
閱讀 3397·2019-08-29 15:19
閱讀 2037·2019-08-29 13:59