给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。
它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。
给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。
题目里居然有一个巨隐藏的重要条件!!!“前 n 个正整数的排列” 这句话,如果没看到的话这道题就无解了。
这道题就是 解码异或后的数组 的 plus 版本,只要我们求出原数组的任意一个元素,就可以推出整个原数组。
由于我们知道 encoded 数组的长度,因此我们可以求出 n ,接着就可以得出原数组 n 个数的异或结果 total ,而通过 encoded 数组我们可以求出除原始数组第一个数的其他所有数的异或结果,将 total 和这个异或结果进行异或操作,即可得出原始数组第一个数,接下来就可以直接使用 解码异或后的数组 的代码进行解题啦!
class Solution:
def decode(self, encoded: List[int]) -> List[int]:
lenth = len(encoded)
total = reduce(xor, range(1, lenth+2)) # 原数组 n 个数的异或结果
for i in range(lenth//2): # 求原数组第一个数
total ^= encoded[2*i+1]
res = [total]
for i in range(lenth):
total ^= encoded[i]
res.append(total)
return res