LeetCode Top 100 Liked Questions 338. Counting Bits (Java版; Medium)

welcome to my blog

LeetCode Top 100 Liked Questions 338. Counting Bits (Java版; Medium)

题目描述

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.

第一次做; 没想到这道题是动态规划; 核心:

优秀的分析, 按照最低位是否为1(奇偶性)分成两种情况讨论

对于所有的数字,只有两类:

奇数:二进制表示中,奇数一定比前面那个偶数多一个 1,因为多的就是最低位的 1。
          举例: 
         0 = 0       1 = 1
         2 = 10      3 = 11
偶数:二进制表示中,偶数中 1 的个数一定和除以 2 之后的那个数一样多。因为最低位是 0,除以 2 就是右移一位,也就是把那个 0 抹掉而已,所以 1 的个数是不变的。
           举例:
          2 = 10       4 = 100       8 = 1000
          3 = 11       6 = 110       12 = 1100
class Solution {
    public int[] countBits(int num) {
        int[] dp = new int[num+1];
        for(int i=1; i<=num; i++){
            //如果当前数是奇数
            if(i%2==1)
                dp[i] = dp[i-1]+1;
            //如果当前数是偶数
            else
                dp[i] = dp[i/2];
        }
        return dp;
    }
}

第一次做; 最直接的想法, 求出每个元素二进制形式下1的个数, 核心: 把某个数二进制形式最右边的1置零,a= a^(a-1)

class Solution {
    public int[] countBits(int num) {
        if(num<0)
            return null;
        int[] res = new int[num+1];
        for(int i=0; i<=num; i++){
            res[i] = core(i);
        }
        return res;
    }
    private int core(int a){
        int count = 0;
        while(a!=0){
            count++;
            a = a&(a-1);
        }
        return count;
    }
}

最优解; 动态规划

public int[] countBits(int num) {
    int[] f = new int[num + 1];
    for (int i=1; i<=num; i++) f[i] = f[i >> 1] + (i & 1);
    return f;
}

你可能感兴趣的:(LeetCode,Top,100,Liked,Questions)