十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶(hù) + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專(zhuān)業(yè)推廣+無(wú)憂(yōu)售后,網(wǎng)站問(wèn)題一站解決
LeetCode 338. Counting Bits
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.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?
給定一個(gè)非負(fù)整數(shù)num。對(duì)于每一個(gè)滿(mǎn)足0 ≤ i ≤ num的數(shù)字i,計(jì)算其數(shù)字的二進(jìn)制表示中1的個(gè)數(shù),并以數(shù)組形式返回。
測(cè)試用例如題目描述。
進(jìn)一步思考:
很容易想到運(yùn)行時(shí)間 O(n*sizeof(integer)) 的解法。但你可以用線(xiàn)性時(shí)間O(n)的一趟算法完成嗎?
空間復(fù)雜度應(yīng)當(dāng)為O(n)。
你可以像老板那樣嗎?不要使用任何內(nèi)建函數(shù)(比如C++的__builtin_popcount)。
提示:
你應(yīng)當(dāng)利用已經(jīng)生成的結(jié)果。
將數(shù)字拆分為諸如 [2-3], [4-7], [8-15] 之類(lèi)的范圍。并且嘗試根據(jù)已經(jīng)生成的范圍產(chǎn)生新的范圍。
3. 數(shù)字的奇偶性可以幫助你計(jì)算1的個(gè)數(shù)嗎?
解法I 利用移位運(yùn)算:
遞推式:ans[n] = ans[n >> 1] + (n & 1)
//c++版本 class Solution { public: vectorcountBits(int num) { //一個(gè)數(shù)組有(0~num)即num+1個(gè)元素,初始化為0 vector v1(num+1,0); for(int i=1;i<=num;i++) { v1[i]=v1[i>>1]+(i&1); } } }
15 / 15 test cases passed.
Status: Accepted
Runtime: 124 ms
Submitted: 0 minutes ago
解法II 利用highbits運(yùn)算:
遞推式:ans[n] = ans[n - highbits(n)] + 1
其中highbits(n)
表示只保留n的最高位得到的數(shù)字。
highbits(n) = 1<例如:
highbits(7) = 4 (7的二進(jìn)制形式為111) highbits(10) = 8 (10的二進(jìn)制形式為1010)解法III 利用按位與運(yùn)算:
遞推式:ans[n] = ans[n & (n - 1)] + 1//c++版本 class Solution { public: vectorcountBits(int num) { //一個(gè)數(shù)組有(0~num)即num+1個(gè)元素,初始化為0 vector v1(num+1,0); for(int i=1;i<=num;i++) { v1[i]=v1[n&(n-1)]+1; } } } 創(chuàng)新互聯(lián)www.cdcxhl.cn,專(zhuān)業(yè)提供香港、美國(guó)云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開(kāi)啟,新人活動(dòng)云服務(wù)器買(mǎi)多久送多久。
名稱(chēng)欄目:leetcode(1)--338.CountingBits-創(chuàng)新互聯(lián)
轉(zhuǎn)載注明:http://m.jiaotiyi.com/article/dcohii.html