LeetCode 338. Counting Bits
創(chuàng)新互聯(lián)公司是一家專注于網(wǎng)站建設(shè)、成都做網(wǎng)站與策劃設(shè)計,漢陽網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10多年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:漢陽等地區(qū)。漢陽做網(wǎng)站價格咨詢:18982081108
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?
給定一個非負(fù)整數(shù)num。對于每一個滿足0 ≤ i ≤ num的數(shù)字i,計算其數(shù)字的二進制表示中1的個數(shù),并以數(shù)組形式返回。
測試用例如題目描述。
進一步思考:
很容易想到運行時間 O(n*sizeof(integer)) 的解法。但你可以用線性時間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] 之類的范圍。并且嘗試根據(jù)已經(jīng)生成的范圍產(chǎn)生新的范圍。
3. 數(shù)字的奇偶性可以幫助你計算1的個數(shù)嗎?
解法I 利用移位運算:
遞推式:ans[n] = ans[n >> 1] + (n & 1)
//c++版本 class Solution { public: vectorcountBits(int num) { //一個數(shù)組有(0~num)即num+1個元素,初始化為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運算:
遞推式:ans[n] = ans[n - highbits(n)] + 1
其中highbits(n)
表示只保留n的最高位得到的數(shù)字。
highbits(n) = 1<例如:
highbits(7) = 4 (7的二進制形式為111) highbits(10) = 8 (10的二進制形式為1010)解法III 利用按位與運算:
遞推式:ans[n] = ans[n & (n - 1)] + 1//c++版本 class Solution { public: vectorcountBits(int num) { //一個數(shù)組有(0~num)即num+1個元素,初始化為0 vector v1(num+1,0); for(int i=1;i<=num;i++) { v1[i]=v1[n&(n-1)]+1; } } }
當(dāng)前標(biāo)題:leetcode(1)--338.CountingBits
本文地址:http://weahome.cn/article/jsgppe.html