leetcode338—Counting Bits

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wilder_ting/article/details/86180255

leetcode338—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 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的个数。用result[i]表示i的二进制表示中1的个数。利用动态规划,找出状态转移表达式result[i]=result[i&i-1]+1

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result(num+1);
        result[0] = 0;
        for(int i = 1 ;i <= num ; i++){
            result[i] = result[i & i-1] + 1;
        }
        return result;
    }
};
posted @ 2018-11-21 13:17 Tingwei_chen 阅读( ...) 评论( ...) 编辑 收藏

猜你喜欢

转载自blog.csdn.net/Wilder_ting/article/details/86180255