LeetCode 题解工作台
最小无法得到的或值
给你一个下标从 0 开始的整数数组 nums 。 如果存在一些整数满足 0 1 2 k ,得到 nums[index 1 ] | nums[index 2 ] | ... | nums[index k ] = x ,那么我们说 x 是 可表达的 。换言之,如果一个整数能由 nums 的某个子序列的或…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
我们从整数 开始考虑,如果 是可表达的,那么它必须出现在数组 `nums` 中;如果 是可表达的,那么它必须出现在数组 `nums` 中;如果 和 都是可表达的,那么它们的或运算 也是可表达的,以此类推。 因此,我们可以枚举 的幂,如果当前枚举的 不在数组 `nums` 中,那么 就是不可表达的最小整数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。
如果存在一些整数满足 0 <= index1 < index2 < ... < indexk < nums.length ,得到 nums[index1] | nums[index2] | ... | nums[indexk] = x ,那么我们说 x 是 可表达的 。换言之,如果一个整数能由 nums 的某个子序列的或运算得到,那么它就是可表达的。
请你返回 nums 不可表达的 最小非零整数 。
示例 1:
输入:nums = [2,1] 输出:4 解释:1 和 2 已经在数组中,因为 nums[0] | nums[1] = 2 | 1 = 3 ,所以 3 是可表达的。由于 4 是不可表达的,所以我们返回 4 。
示例 2:
输入:nums = [5,3,2] 输出:1 解释:1 是最小不可表达的数字。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 109
解题思路
方法一:枚举 2 的幂
我们从整数 开始考虑,如果 是可表达的,那么它必须出现在数组 nums 中;如果 是可表达的,那么它必须出现在数组 nums 中;如果 和 都是可表达的,那么它们的或运算 也是可表达的,以此类推。
因此,我们可以枚举 的幂,如果当前枚举的 不在数组 nums 中,那么 就是不可表达的最小整数。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 nums 的长度和数组 nums 中的最大值。
class Solution:
def minImpossibleOR(self, nums: List[int]) -> int:
s = set(nums)
return next(1 << i for i in range(32) if 1 << i not in s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the method: using bit tracking or set expansion is O(n * number_of_bits), space complexity is O(number_of_bits) or O(n) depending on tracking OR results. Full subsequence enumeration is infeasible. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on cumulative bit coverage and subsequence ORs
- question_mark
Check for powers of two gaps to identify missing numbers
- question_mark
Efficiency matters: avoid generating all subsequences explicitly
常见陷阱
外企场景- error
Assuming the missing number is max(nums)+1 without checking OR combinations
- error
Enumerating all subsequences leading to timeouts
- error
Ignoring bitwise properties leading to incorrect smallest number
进阶变体
外企场景- arrow_right_alt
Find maximum number not expressible using at most k elements
- arrow_right_alt
Handle arrays with negative numbers and modified OR rules
- arrow_right_alt
Compute count of unexpressible integers under given constraints