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.
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.
給予一非負整數num。對每個符合0 ≤ i ≤ num的數字i,去計算它的二進制表示法中有多少個1並用陣列回傳答案。
進階:
- 這很容易就能找到一個答案是在執行時間 O(n*sizeof(integer)) 中。但你可以完成在線性時間 O(n) 並在一次掃描(pass這邊翻掃描,不知道怎麼翻比較好XD 反正就是只跑一輪陣列)中完成嗎?
- 空間複雜度應該在O(n)。
- 你可以像個boss一樣地完成嗎?不使用任何內建的函式庫,例如C++中的 builtin_popcount 或是其他語言中任何相似的東西來完成該題。
0 ~ 7
的二進制轉換:Base 10 | Base 2 |
---|---|
0 | 0 |
1 | 1 |
2 | 10 |
3 | 11 |
4 | 100 |
5 | 101 |
6 | 110 |
7 | 111 |
2 ~ 3
是0 ~ 1
最前面加上1
;4 ~ 7
是0 ~ 3
最前面加上1
。2
的平方去當作切割點,後面的都是前面的值+1
。我們只要先初始化最前面的值,後面的都可以用前面算出來。num
次,因此壓在O(n)的時間複雜度中。LeetCode
C++