美文网首页
AC 剑指 Offer II 003. 前 n 个数字二进制中

AC 剑指 Offer II 003. 前 n 个数字二进制中

作者: itbird01 | 来源:发表于2022-03-29 15:35 被阅读0次

给定一个非负整数 n ,请计算 0 到 n 之间的每个数字的二进制表示中 1 的个数,并输出一个数组。

示例 1:
输入: n = 2
输出: [0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10
示例 2:

输入: n = 5
输出: [0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

说明 :
0 <= n <= 105

进阶:
给出时间复杂度为 O(n*sizeof(integer)) 的解答非常容易。但你可以在线性时间 O(n) 内用一趟扫描做到吗?
要求算法的空间复杂度为 O(n) 。
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount )来执行此操作。

解法1

把每个数字,通过java的Integer.toBinaryString(i)转换为二进制字符串,然后遍历,统计其中1的个数

class Solution {
    /**
     * @Title: countBits
     * @Description:
     * @author: itbird
     * @date 2022年3月29日 下午3:11:07
     * @param n
     * @return int[] 时间复杂度: O(n*sizeOf(n)) 空间复杂度: O(n)
     */
    public int[] countBits(int n) {
        int[] res = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            res[i] = getOneNums(i);
        }
        return res;
    }

    /**
     * @Title: getOneNums
     * @Description: 获取一个数字二进制表示中,有多少个1
     * @author: itbird
     * @date 2022年3月29日 下午3:13:32
     * @param i
     * @return int 时间复杂度: O(sizeOf(n)) 空间复杂度: O(n)
     */
    private int getOneNums(int i) {
        String binaryString = Integer.toBinaryString(i);
        int sum = 0;
        for (int j = 0; j < binaryString.length(); j++) {
            if (binaryString.charAt(j) == '1') {
                sum++;
            }
        }
        return sum;
    }
}

解法2

动态规划,偶数的2倍,这两个数1的个数肯定是相同的;奇数的1的个数,肯定是前面偶数的1的个数+1;

class Solution {
    /**
     * @Title: countBits
     * @Description:
     * @author: itbird
     * @date 2022年3月29日 下午3:11:07
     * @param n
     * @return int[] 时间复杂度: O(n) 空间复杂度: O(n)
     */
    public int[] countBits(int n) {
        int[] res = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            if ((i & 1) == 1) {
                // 如果i是奇数,则比前一位偶数,多一个1
                res[i] = res[i >> 1] + 1;
            } else {
                // 如果i是偶数,则和前面最邻近的偶数,1的个数相等
                res[i] = res[i >> 1];
            }
        }
        return res;
    }
}

相关文章

网友评论

      本文标题:AC 剑指 Offer II 003. 前 n 个数字二进制中

      本文链接:https://www.haomeiwen.com/subject/xjovjrtx.html