您好,登錄后才能下訂單哦!
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è)滿足0 ≤ i ≤ num的數(shù)字i,計(jì)算其數(shù)字的二進(jìn)制表示中1的個(gè)數(shù),并以數(shù)組形式返回。
測(cè)試用例如題目描述。
進(jìn)一步思考:
很容易想到運(yùn)行時(shí)間 O(n*sizeof(integer)) 的解法。但你可以用線性時(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: vector<int>countBits(int num) { //一個(gè)數(shù)組有(0~num)即num+1個(gè)元素,初始化為0 vector<int> 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<<int(math.log(x,2)) math.log()不是c++/c的函數(shù),java中有
例如:
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: vector<int>countBits(int num) { //一個(gè)數(shù)組有(0~num)即num+1個(gè)元素,初始化為0 vector<int> v1(num+1,0); for(int i=1;i<=num;i++) { v1[i]=v1[n&(n-1)]+1; } } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。