Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

338. 比特位计数 #141

Open
S-T-D opened this issue Sep 6, 2021 · 0 comments
Open

338. 比特位计数 #141

S-T-D opened this issue Sep 6, 2021 · 0 comments
Labels

Comments

@S-T-D
Copy link
Owner

S-T-D commented Sep 6, 2021

原题地址

338. 比特位计数

 

题目描述

给定一个非负整数 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)来执行此操作

 

题解 —— api

思路

代码

/**
 * @param {number} n
 * @return {number[]}
 */
var countBits = function(n) {
    const res = [];
    for (let i = 0; i <= n; i++) {
        const s = i.toString(2);
        let count = 0;
        for (const num of s) {
            if (num === '1') count++;
        }
        res.push(count);
    }
    return res;
};

复杂度

  • 时间:O(n*数字二进制长度)
  • 空间:O(n)

 

题解 —— 奇偶性

思路

参考

代码

/**
 * @param {number} n
 * @return {number[]}
 */
var countBits = function(n) {
    const res = [0];
    for (let i = 1; i <= n; i++) {
        // 奇数:比前面一个数多 1
        if (i % 2 === 1) {
            res[i] = res[i - 1] + 1;
        } else {
            // 偶数:偶数中 1 的个数一定和除以 2 之后的那个数一样多。因为最低位是 0,除以 2 就是右移一位,也就是把那个 0 抹掉而已,所以 1 的个数是不变的。
            res[i] = res[i / 2];
        }
    }
    return res;
};

复杂度

  • 时间:O(n)
  • 空间:O(n)

 

@S-T-D S-T-D added the 数组 label Sep 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant