LeetCode 题解工作台
可被 5 整除的二进制前缀
给定一个二进制数组 nums ( 索引从0开始 )。 我们将 x i 定义为其二进制表示形式为子数组 nums[0..i] (从最高有效位到最低有效位)。 例如,如果 nums =[1,0,1] ,那么 x 0 = 1 , x 1 = 2 , 和 x 2 = 5 。 返回布尔值列表 answer ,…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·结合·位运算·操作
答案摘要
我们用一个变量 来表示当前的二进制前缀,然后遍历数组 ,对于每个元素 ,我们将 左移一位,然后加上 ,再对 取模,判断是否等于 ,如果等于 ,则说明当前的二进制前缀可以被 整除,我们将 加入答案数组,否则将 加入答案数组。 时间复杂度 ,忽略答案数组的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给定一个二进制数组 nums ( 索引从0开始 )。
我们将xi 定义为其二进制表示形式为子数组 nums[0..i] (从最高有效位到最低有效位)。
- 例如,如果
nums =[1,0,1],那么x0 = 1,x1 = 2, 和x2 = 5。
返回布尔值列表 answer,只有当 xi 可以被 5 整除时,答案 answer[i] 为 true,否则为 false。
示例 1:
输入:nums = [0,1,1] 输出:[true,false,false] 解释: 输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为 true 。
示例 2:
输入:nums = [1,1,1] 输出:[false,false,false]
提示:
1 <= nums.length <= 105nums[i]仅为0或1
解题思路
方法一:模拟
我们用一个变量 来表示当前的二进制前缀,然后遍历数组 ,对于每个元素 ,我们将 左移一位,然后加上 ,再对 取模,判断是否等于 ,如果等于 ,则说明当前的二进制前缀可以被 整除,我们将 加入答案数组,否则将 加入答案数组。
时间复杂度 ,忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
ans = []
x = 0
for v in nums:
x = (x << 1 | v) % 5
ans.append(x == 0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) as we iterate through the array once. Space complexity is O(n) for the answer array; extra space is O(1) since only the current modulo is tracked. Large arrays are handled efficiently due to modulo arithmetic and bit shift updates. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on the binary-to-decimal conversion via prefix computation.
- question_mark
Look for constant space optimization using modulo rather than full number storage.
- question_mark
Expect clarity in handling edge cases like leading zeros and small arrays.
常见陷阱
外企场景- error
Attempting to convert each prefix to decimal directly, causing overflow.
- error
Ignoring modulo arithmetic, resulting in incorrect divisibility checks.
- error
Misinterpreting the binary order and updating prefixes incorrectly.
进阶变体
外企场景- arrow_right_alt
Check divisibility by other numbers like 3 or 7 instead of 5 using the same prefix technique.
- arrow_right_alt
Compute sums of binary prefixes rather than divisibility flags.
- arrow_right_alt
Return indices of prefixes divisible by 5 instead of boolean array.