调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
困难
相关标签
相关企业
提示

给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。

一次操作中,你可以选择 nums 中满足 0 <= i < nums.length - 1 的一个下标 i ,并将 nums[i] 和 nums[i + 1] 替换为数字 nums[i] & nums[i + 1] ,其中 & 表示按位 AND 操作。

请你返回 至多 k 次操作以内,使 nums 中所有剩余元素按位 OR 结果的 最小值 。

 

示例 1:

输入:nums = [3,5,3,2,7], k = 2
输出:3
解释:执行以下操作:
1. 将 nums[0] 和 nums[1] 替换为 (nums[0] & nums[1]) ,得到 nums 为 [1,3,2,7] 。
2. 将 nums[2] 和 nums[3] 替换为 (nums[2] & nums[3]) ,得到 nums 为 [1,3,2] 。
最终数组的按位或值为 3 。
3 是 k 次操作以内,可以得到的剩余元素的最小按位或值。

示例 2:

输入:nums = [7,3,15,14,2,8], k = 4
输出:2
解释:执行以下操作:
1. 将 nums[0] 和 nums[1] 替换为 (nums[0] & nums[1]) ,得到 nums 为 [3,15,14,2,8] 。
2. 将 nums[0] 和 nums[1] 替换为 (nums[0] & nums[1]) ,得到 nums 为 [3,14,2,8] 。
3. 将 nums[0] 和 nums[1] 替换为 (nums[0] & nums[1]) ,得到 nums 为 [2,2,8] 。
4. 将 nums[1] 和 nums[2] 替换为 (nums[1] & nums[2]) ,得到 nums 为 [2,0] 。
最终数组的按位或值为 2 。
2 是 k 次操作以内,可以得到的剩余元素的最小按位或值。

示例 3:

输入:nums = [10,7,10,3,9,14,9,4], k = 1
输出:15
解释:不执行任何操作,nums 的按位或值为 15 。
15 是 k 次操作以内,可以得到的剩余元素的最小按位或值。

 

提示:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] < 230
  • 0 <= k < nums.length
通过次数
1.8K
提交次数
4.8K
通过率
38.3%


相关企业

提示 1
From the most significant bit to the least significant bit, maintain the bits that will not be included in the final answer in a variable mask.

提示 2
For a fixed bit, add it to mask then check if there exists some sequence of k operations such that mask & answer == 0 where answer is the bitwise-or of the remaining elements of nums. If there is no such sequence of operations, remove the current bit from mask. How can we perform this check?

提示 3
Let x be the bitwise-and of all elements of nums. If x AND mask != 0, there is no sequence of operations that satisfies the condition in the previous hint. This is because even if we perform this operation n - 1 times on the array, we will end up with x as the final element.

提示 4
Otherwise, there exists at least one such sequence. It is sufficient to check if the number of operations in such a sequence is less than k. Let’s calculate the minimum number of operations in such a sequence.

提示 5
Iterate over the array from left to right, if nums[i] & mask != 0, apply the operation on index i.

提示 6
After iterating over all elements, let x be the bitwise-and of all elements of nums. If x == 0, then we have found the minimum number of operations. Otherwise, It can be proven that we need exactly one more operation so that x == 0.

提示 7
The condition in the second hint is satisfied if and only if the minimum number of operations is less than or equal to k.


评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
nums =
[3,5,3,2,7]
k =
2
Source