LeetCode 题解工作台
解码异或后的排列
给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。 它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded =…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
我们注意到,数组 是前 个正整数的排列,因此 的所有元素的异或和为 $1 \oplus 2 \oplus \cdots \oplus n$,记为 。而 $encode[i]=perm[i] \oplus perm[i+1]$,如果我们将 的所有元素的异或和记为 ,则 $perm[n-1]=a \oplus b$。知道了 的最后一个元素,我们就可以通过逆序遍历数组 求出 的所有元素。 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。
它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。
给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。
示例 1:
输入:encoded = [3,1] 输出:[1,2,3] 解释:如果 perm = [1,2,3] ,那么 encoded = [1 XOR 2,2 XOR 3] = [3,1]
示例 2:
输入:encoded = [6,5,4,6] 输出:[2,4,1,5,3]
提示:
3 <= n < 105n是奇数。encoded.length == n - 1
解题思路
方法一:位运算
我们注意到,数组 是前 个正整数的排列,因此 的所有元素的异或和为 ,记为 。而 ,如果我们将 的所有元素的异或和记为 ,则 。知道了 的最后一个元素,我们就可以通过逆序遍历数组 求出 的所有元素。
时间复杂度 ,其中 为数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def decode(self, encoded: List[int]) -> List[int]:
n = len(encoded) + 1
a = b = 0
for i in range(0, n - 1, 2):
a ^= encoded[i]
for i in range(1, n + 1):
b ^= i
perm = [0] * n
perm[-1] = a ^ b
for i in range(n - 2, -1, -1):
perm[i] = encoded[i] ^ perm[i + 1]
return perm
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They mention that n is odd, which is the clue that alternating encoded positions reveal all permutation values except the first.
- question_mark
They hint at XOR from 1 to n, pushing you to combine permutation-wide XOR with local neighbor XOR relationships.
- question_mark
They care whether you can derive perm[0] mathematically instead of guessing and validating candidates.
常见陷阱
外企场景- error
XORing the wrong encoded indices, such as starting at index 0 instead of index 1, which breaks the cancellation pattern needed to isolate perm[0].
- error
Forgetting that the answer is a permutation of 1 through n, so total XOR must be computed from that full range, not from encoded values.
- error
Building the array with the wrong recurrence direction, because perm[i + 1] must be perm[i] XOR encoded[i], not the other way around.
进阶变体
外企场景- arrow_right_alt
Return the same permutation when encoded is streamed, requiring you to delay reconstruction until perm[0] is derived from the full alternating XOR.
- arrow_right_alt
Decode a related array where the original numbers are distinct but not guaranteed to be 1 through n, removing the direct total XOR shortcut.
- arrow_right_alt
Handle the non-odd case and explain why this exact alternating-XOR trick no longer isolates a single starting value.