LeetCode 题解工作台
构造最小位运算数组 II
给你一个长度为 n 的 质数 数组 nums 。你的任务是返回一个长度为 n 的数组 ans ,对于每个下标 i ,以下 条件 均成立: ans[i] OR (ans[i] + 1) == nums[i] 除此以外,你需要 最小化 结果数组里每一个 ans[i] 。 如果没法找到符合 条件 的 an…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
对于一个整数 ,满足 $a \lor (a + 1)$ 的结果一定为奇数,因此,如果 是偶数,那么 一定不存在,直接返回 。本题中 是质数,判断是否是偶数,只需要判断是否等于 即可。 如果 是奇数,假设 $\text{nums[i]} = \text{0b1101101}$,由于 $a \lor (a + 1) = \text{nums[i]}$,等价于将 的最后一个为 的二进制位变…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个长度为 n 的 质数 数组 nums 。你的任务是返回一个长度为 n 的数组 ans ,对于每个下标 i ,以下 条件 均成立:
ans[i] OR (ans[i] + 1) == nums[i]
除此以外,你需要 最小化 结果数组里每一个 ans[i] 。
如果没法找到符合 条件 的 ans[i] ,那么 ans[i] = -1 。
质数 指的是一个大于 1 的自然数,且它只有 1 和自己两个因数。
示例 1:
输入:nums = [2,3,5,7]
输出:[-1,1,4,3]
解释:
- 对于
i = 0,不存在ans[0]满足ans[0] OR (ans[0] + 1) = 2,所以ans[0] = -1。 - 对于
i = 1,满足ans[1] OR (ans[1] + 1) = 3的最小ans[1]为1,因为1 OR (1 + 1) = 3。 - 对于
i = 2,满足ans[2] OR (ans[2] + 1) = 5的最小ans[2]为4,因为4 OR (4 + 1) = 5。 - 对于
i = 3,满足ans[3] OR (ans[3] + 1) = 7的最小ans[3]为3,因为3 OR (3 + 1) = 7。
示例 2:
输入:nums = [11,13,31]
输出:[9,12,15]
解释:
- 对于
i = 0,满足ans[0] OR (ans[0] + 1) = 11的最小ans[0]为9,因为9 OR (9 + 1) = 11。 - 对于
i = 1,满足ans[1] OR (ans[1] + 1) = 13的最小ans[1]为12,因为12 OR (12 + 1) = 13。 - 对于
i = 2,满足ans[2] OR (ans[2] + 1) = 31的最小ans[2]为15,因为15 OR (15 + 1) = 31。
提示:
1 <= nums.length <= 1002 <= nums[i] <= 109nums[i]是一个质数。
解题思路
方法一:位运算
对于一个整数 ,满足 的结果一定为奇数,因此,如果 是偶数,那么 一定不存在,直接返回 。本题中 是质数,判断是否是偶数,只需要判断是否等于 即可。
如果 是奇数,假设 ,由于 ,等价于将 的最后一个为 的二进制位变为 。那么求解 ,就等价于将 的最后一个 的下一位 变为 。我们只需要从低位(下标为 )开始遍历,找到第一个为 的二进制位,如果是第 位,那么我们就将 的第 位变为 ,即 。
遍历所有的 ,即可得到答案。
时间复杂度 ,其中 和 分别是数组 的长度和数组中的最大值。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def minBitwiseArray(self, nums: List[int]) -> List[int]:
ans = []
for x in nums:
if x == 2:
ans.append(-1)
else:
for i in range(1, 32):
if x >> i & 1 ^ 1:
ans.append(x ^ 1 << (i - 1))
break
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on iterating through each nums[i] and computing binary manipulations, roughly O(n * log(nums[i])). Space complexity is O(n) for storing the resulting ans array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on bitwise OR patterns rather than arithmetic approaches.
- question_mark
Consider how minimizing each ans[i] might conflict with satisfying the OR condition.
- question_mark
Expect questions on handling edge cases when nums[i] has consecutive ones in binary.
常见陷阱
外企场景- error
Assuming ans[i] can be nums[i]-1 without verifying the OR condition.
- error
Ignoring binary representation patterns that affect minimal solutions.
- error
Failing to handle small prime values or negative minimal results correctly.
进阶变体
外企场景- arrow_right_alt
Construct the minimum array for bitwise AND instead of OR.
- arrow_right_alt
Allow composite numbers instead of only prime numbers in nums.
- arrow_right_alt
Find ans array maximizing values instead of minimizing while satisfying OR.