LeetCode 338. 位元位計數(C、C++、python)
阿新 • • 發佈:2018-11-21
給定一個非負整數 num。對於 0 ≤ i ≤ num 範圍中的每個數字 i ,計算其二進位制數中的 1 的數目並將它們作為陣列返回。
示例 1:
輸入: 2 輸出: [0,1,1]
示例 2:
輸入: 5
輸出: [0,1,1,2,1,2]
進階:
給出時間複雜度為O(n*sizeof(integer))的解答非常容易。但你可以線上性時間O(n)內用一趟掃描做到嗎?
要求演算法的空間複雜度為O(n)。
你能進一步完善解法嗎?要求在C++或任何其他語言中不使用任何內建函式(如 C++ 中的 __builtin_popcount
C
/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* countBits(int num, int* returnSize) { int* res=(int*)malloc(sizeof(int)*(num+1)); res[0]=0; for(int i=1;i<=num;i++) { res[i]=res[i>>1]+i%2; } *returnSize=num+1; return res; }
C++
class Solution {
public:
vector<int> countBits(int num)
{
vector<int> res(num+1,0);
for(int i=1;i<=num;i++)
{
res[i]=res[i>>1]+i%2;
}
return res;
}
};
python
class Solution: def countBits(self, num): """ :type num: int :rtype: List[int] """ res=[0] for i in range(1,num+1): res.append(res[i//2]+i%2) return res