LeetCode 题解工作台

比特位计数

给你一个整数 n ,对于 0 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。 示例 1: 输入: n = 2 输出: [0,1,1] 解释: 0 --> 0 1 --> 1 2 --> 10 示例 2: 输入: n = 5 输出: [0,1,…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 状态·转移·动态规划

bolt

答案摘要

我们直接枚举 $0 \leq i \leq n$ 中的每个数,对于每个数 ,我们用库函数或者 运算得到 中二进制位 的个数。 时间复杂度 $O(n \times \log n)$,忽略答案的空间消耗,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。

 

示例 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 log n) 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗?
  • 你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount
lightbulb

解题思路

方法一:位运算

我们直接枚举 0in0 \leq i \leq n 中的每个数,对于每个数 ii,我们用库函数或者 lowbitlowbit 运算得到 ii 中二进制位 11 的个数。

时间复杂度 O(n×logn)O(n \times \log n),忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def countBits(self, n: int) -> List[int]:
        return [i.bit_count() for i in range(n + 1)]
speed

复杂度分析

指标
时间complexity is O(n) because each dp[i] is computed in constant time using previously computed values. Space complexity is O(n) for the dp array storing counts for 0 through n.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expect recognition of the state transition pattern for efficient DP.

  • question_mark

    Look for correct use of i & (i - 1) for bit manipulation optimization.

  • question_mark

    Check if candidate avoids naive per-number bit counting loops.

warning

常见陷阱

外企场景
  • error

    Recomputing bit counts for each i instead of using DP, leading to O(n log n) time.

  • error

    Forgetting to initialize dp[0], causing index errors or incorrect base cases.

  • error

    Misusing i & (i - 1) logic, resulting in off-by-one errors in counts.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the number of 0 bits instead of 1 bits in each number from 0 to n.

  • arrow_right_alt

    Return bit counts only for odd numbers up to n.

  • arrow_right_alt

    Calculate bit counts for numbers in a given range [a, b] using the same DP approach.

help

常见问题

外企场景

比特位计数题解:状态·转移·动态规划 | LeetCode #338 简单