LeetCode 题解工作台
数组最后一个元素的最小值
给你两个整数 n 和 x 。你需要构造一个长度为 n 的 正整数 数组 nums ,对于所有 0 ,满足 nums[i + 1] 大于 nums[i] ,并且数组 nums 中所有元素的按位 AND 运算结果为 x 。 返回 nums[n - 1] 可能的 最小 值。 示例 1: 输入: n = 3…
1
题型
5
代码语言
3
相关题
当前训练重点
中等 · 位运算·操作·driven·solution·strategy
答案摘要
根据题目描述,要使得数组的最后一个元素尽可能小,且数组中的元素按位与的结果为 ,那么数组的第一个元素必须为 。 假设 的二进制表示为 ,那么数组序列为 , , , ...
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路
题目描述
给你两个整数 n 和 x 。你需要构造一个长度为 n 的 正整数 数组 nums ,对于所有 0 <= i < n - 1 ,满足 nums[i + 1] 大于 nums[i] ,并且数组 nums 中所有元素的按位 AND 运算结果为 x 。
返回 nums[n - 1] 可能的 最小 值。
示例 1:
输入:n = 3, x = 4
输出:6
解释:
数组 nums 可以是 [4,5,6] ,最后一个元素为 6 。
示例 2:
输入:n = 2, x = 7
输出:15
解释:
数组 nums 可以是 [7,15] ,最后一个元素为 15 。
提示:
1 <= n, x <= 108
解题思路
方法一:贪心 + 位运算
根据题目描述,要使得数组的最后一个元素尽可能小,且数组中的元素按位与的结果为 ,那么数组的第一个元素必须为 。
假设 的二进制表示为 ,那么数组序列为 , , , ...
如果我们忽略掉下划线部分,那么数组序列为 , , , ...,第一项为 ,那么第 项为 。
因此,答案就是在 的基础上,将 的二进制的每一位依次填入 的二进制中的 位。
时间复杂度 ,空间复杂度 。
class Solution:
def minEnd(self, n: int, x: int) -> int:
n -= 1
ans = x
for i in range(31):
if x >> i & 1 ^ 1:
ans |= (n & 1) << i
n >>= 1
ans |= n << 31
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\log n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Tests understanding of bitwise operations and their application in problem-solving.
- question_mark
Evaluates the candidate’s ability to construct an array with constraints using bit manipulation.
- question_mark
Assesses knowledge of optimization techniques when dealing with bitwise AND operations.
常见陷阱
外企场景- error
Not properly understanding the bitwise AND operation and how it impacts the selection of elements.
- error
Incorrectly merging values without ensuring that the array remains strictly increasing.
- error
Failing to minimize the last element while maintaining the required bitwise AND condition.
进阶变体
外企场景- arrow_right_alt
Change the number of elements in the array and observe how the merging process scales.
- arrow_right_alt
Modify the bitwise AND condition to use a different value and test for edge cases.
- arrow_right_alt
Introduce additional constraints on the array elements, such as limits on individual values or their bitwise characteristics.