zoukankan      html  css  js  c++  java
  • 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.

    公众号每日一题有详细讲解分析:

    P 题的难点在于构建最优子结构。只要构造了最优子结构,一般就比较容易解题了。构造最优子结构的方法有两种:倒推发现 n 与 0 到 n - 1 的关系;使用 DFS 和 递归 方法,从 0 到 n 发现规律。

    今天这道题的解法试图通过观察其特点发现规律。这也是一般性的思考问题的方法:通过画图,将抽象的问题具体化,通过具体的例子来发现规律,最后推广到 n 的规模。

    class Solution {
    public:
        vector<int> countBits(int num) {
            vector<int> res(num + 1, 0);
            res[1] = 1;
            for ( int i = 0; i <= num; i++)
            {
                if ( i % 2 == 0)
                {
                    res[i] = res[i/2];
                }
                else
                {
                    res[i] = res[i/2] + 1;
                }
            }
            return res;
        }
    };
    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 & 1);
            }
            return res;
        }
    };
  • 相关阅读:
    mysql数据库小常识
    CSP.ac #61乘积求和
    CSP.ac #60
    CSP.ac低仿机器人(T1-1)
    题解:swj社会摇基础第一课
    题解:T103180 しろは的军训列队
    关 于 篮 球
    关 于 自 恋
    题解:T103342 Problem A. 最近公共祖先
    关 于 匀 变 速 直 线 运 动 的 推 论
  • 原文地址:https://www.cnblogs.com/simplepaul/p/6790686.html
Copyright © 2011-2022 走看看