您好,登錄后才能下訂單哦!
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?
給定一個非負整數num。對于每一個滿足0 ≤ i ≤ num的數字i,計算其數字的二進制表示中1的個數,并以數組形式返回。
測試用例如題目描述。
進一步思考:
很容易想到運行時間 O(n*sizeof(integer)) 的解法。但你可以用線性時間O(n)的一趟算法完成嗎?
空間復雜度應當為O(n)。
你可以像老板那樣嗎?不要使用任何內建函數(比如C++的__builtin_popcount)。
提示:
你應當利用已經生成的結果。
將數字拆分為諸如 [2-3], [4-7], [8-15] 之類的范圍。并且嘗試根據已經生成的范圍產生新的范圍。
3. 數字的奇偶性可以幫助你計算1的個數嗎?
解法I 利用移位運算:
遞推式:ans[n] = ans[n >> 1] + (n & 1)
//c++版本 class Solution { public: vector<int>countBits(int num) { //一個數組有(0~num)即num+1個元素,初始化為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運算:
遞推式:ans[n] = ans[n - highbits(n)] + 1
其中highbits(n)
表示只保留n的最高位得到的數字。
highbits(n) = 1<<int(math.log(x,2)) math.log()不是c++/c的函數,java中有
例如:
highbits(7) = 4 (7的二進制形式為111) highbits(10) = 8 (10的二進制形式為1010)
解法III 利用按位與運算:
遞推式:ans[n] = ans[n & (n - 1)] + 1
//c++版本 class Solution { public: vector<int>countBits(int num) { //一個數組有(0~num)即num+1個元素,初始化為0 vector<int> v1(num+1,0); for(int i=1;i<=num;i++) { v1[i]=v1[n&(n-1)]+1; } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。