LeetCode 题解工作台
找出前缀异或的原始数组
给你一个长度为 n 的 整数 数组 pref 。找出并返回满足下述条件且长度为 n 的数组 arr : pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i] . 注意 ^ 表示 按位异或 (bitwise-xor)运算。 可以证明答案是 唯一 的。 示例 1: 输入: p…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
根据题意,我们有式子一: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个长度为 n 的 整数 数组 pref 。找出并返回满足下述条件且长度为 n 的数组 arr :
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
注意 ^ 表示 按位异或(bitwise-xor)运算。
可以证明答案是 唯一 的。
示例 1:
输入:pref = [5,2,0,3,1] 输出:[5,7,2,3,2] 解释:从数组 [5,7,2,3,2] 可以得到如下结果: - pref[0] = 5 - pref[1] = 5 ^ 7 = 2 - pref[2] = 5 ^ 7 ^ 2 = 0 - pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3 - pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1
示例 2:
输入:pref = [13] 输出:[13] 解释:pref[0] = arr[0] = 13
提示:
1 <= pref.length <= 1050 <= pref[i] <= 106
解题思路
方法一:位运算
根据题意,我们有式子一:
所以,也就有式子二:
我们将式子一二进行异或运算,得到:
即答案数组的每一项都是前缀异或数组的相邻两项进行异或运算得到的。
时间复杂度 ,其中 为前缀异或数组的长度。忽略答案的空间消耗,空间复杂度 。
class Solution:
def findArray(self, pref: List[int]) -> List[int]:
return [a ^ b for a, b in pairwise([0] + pref)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate describe the properties of XOR and how it can be used to reverse the prefix array?
- question_mark
Do they understand the iterative nature of the problem and can they apply the XOR operation correctly?
- question_mark
Can they optimize the solution to handle large inputs efficiently?
常见陷阱
外企场景- error
Misunderstanding the XOR properties and attempting a more complex solution than necessary.
- error
Failing to handle edge cases where the array length is minimal or contains zeros.
- error
Overcomplicating the solution by introducing unnecessary operations or data structures.
进阶变体
外企场景- arrow_right_alt
What if the prefix XOR array is given in reverse order? Can you adjust the approach?
- arrow_right_alt
What happens if the array size is much larger? How would you ensure your solution is still efficient?
- arrow_right_alt
Could a more complex data structure be used for a different variant of this problem?