LeetCode 题解工作台
按位或最大的最小子数组长度
给你一个长度为 n 下标从 0 开始的数组 nums ,数组中所有数字均为非负整数。对于 0 到 n - 1 之间的每一个下标 i ,你需要找出 nums 中一个 最小 非空子数组,它的起始位置为 i (包含这个位置),同时有 最大 的 按位或 运算值 。 换言之,令 B ij 表示子数组 nums…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
要找到每个以 作为起始位置的最短子数组,满足或运算结果最大,那么必须让这个结果的 尽可能多。 我们用一个 位大小的数组 来记录每一位 最早出现的位置。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个长度为 n 下标从 0 开始的数组 nums ,数组中所有数字均为非负整数。对于 0 到 n - 1 之间的每一个下标 i ,你需要找出 nums 中一个 最小 非空子数组,它的起始位置为 i (包含这个位置),同时有 最大 的 按位或运算值 。
- 换言之,令
Bij表示子数组nums[i...j]的按位或运算的结果,你需要找到一个起始位置为i的最小子数组,这个子数组的按位或运算的结果等于max(Bik),其中i <= k <= n - 1。
一个数组的按位或运算值是这个数组里所有数字按位或运算的结果。
请你返回一个大小为 n 的整数数组 answer,其中 answer[i]是开始位置为 i ,按位或运算结果最大,且 最短 子数组的长度。
子数组 是数组里一段连续非空元素组成的序列。
示例 1:
输入:nums = [1,0,2,1,3] 输出:[3,3,2,2,1] 解释: 任何位置开始,最大按位或运算的结果都是 3 。 - 下标 0 处,能得到结果 3 的最短子数组是 [1,0,2] 。 - 下标 1 处,能得到结果 3 的最短子数组是 [0,2,1] 。 - 下标 2 处,能得到结果 3 的最短子数组是 [2,1] 。 - 下标 3 处,能得到结果 3 的最短子数组是 [1,3] 。 - 下标 4 处,能得到结果 3 的最短子数组是 [3] 。 所以我们返回 [3,3,2,2,1] 。
示例 2:
输入:nums = [1,2] 输出:[2,1] 解释: 下标 0 处,能得到最大按位或运算值的最短子数组长度为 2 。 下标 1 处,能得到最大按位或运算值的最短子数组长度为 1 。 所以我们返回 [2,1] 。
提示:
n == nums.length1 <= n <= 1050 <= nums[i] <= 109
解题思路
方法一:逆序遍历
要找到每个以 作为起始位置的最短子数组,满足或运算结果最大,那么必须让这个结果的 尽可能多。
我们用一个 位大小的数组 来记录每一位 最早出现的位置。
逆序遍历数组 ,对于 数字中的第 位,如果为 ,那么 就是 。否则如果 不为 ,说明右侧找到了满足第 位为 的数字,更新长度。
时间复杂度 。其中 为数组 的长度,而 为数组 中的最大值。
class Solution:
def smallestSubarrays(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [1] * n
f = [-1] * 32
for i in range(n - 1, -1, -1):
t = 1
for j in range(32):
if (nums[i] >> j) & 1:
f[j] = i
elif f[j] != -1:
t = max(t, f[j] - i + 1)
ans[i] = t
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \times \log C) |
| 空间 | O(\log C) |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to implement efficient binary search within the context of a bitwise operation.
- question_mark
Check if the candidate understands how bit manipulation impacts the OR value in subarrays.
- question_mark
Evaluate the candidate's use of sliding window techniques to optimize the search for the shortest subarray.
常见陷阱
外企场景- error
Candidates may attempt brute force solutions without considering efficient binary search or bit manipulation.
- error
Not properly managing the sliding window can lead to incorrect or suboptimal subarray lengths.
- error
Failing to handle edge cases, like arrays with only one element or all elements being zero.
进阶变体
外企场景- arrow_right_alt
Consider variations where the array elements are restricted to smaller ranges, which may simplify the bit manipulation part.
- arrow_right_alt
Try different approaches where the array is sorted or contains duplicate values, potentially affecting the bitwise OR result.
- arrow_right_alt
Modify the problem to calculate the smallest subarray with a specific target OR value instead of the maximum OR.