Counting Bits (M)
題目
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 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [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.
題意
計算整數0-num的每一個數的二進制中的1的個數,要求時間復雜度為\(O(N)\),而非\(O(kN)\),
思路
個人的做法是針對每一個整數num,它二進制中1的個數,就等于把它最高位的1去掉后得到的整數的二進制中1的個數加1,如8的二進制為1000,而去掉最高位1得到的整數為0,所以8的二進制中1的個數為0+1=1,
更巧妙的方法是對于每個整數i,i&(i-1)的結果就相當于把i最右邊的1變為0,這樣很容易得到count[i] = count[i&(i-1)] + 1,
代碼實作
Java
去掉最高位
class Solution {
public int[] countBits(int num) {
int[] count = new int[num + 1];
count[0] = 0;
int size = 1;
int cnt = 0;
for (int i = 1; i <= num; i++) {
if (cnt == size) {
cnt = 0;
size *= 2;
}
count[i] = count[i - size] + 1;
cnt++;
}
return count;
}
}
去掉最右1
class Solution {
public int[] countBits(int num) {
int[] count = new int[num + 1];
count[0] = 0;
for (int i = 1; i <= num; i++) {
count[i] = count[i & (i - 1)] + 1;
}
return count;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/33850.html
標籤:其他
