leetcode-1734 解码异或后的排列
解题思路
- 异或运算特性
\[a \bigoplus b=c\ \ \ \ \ \ c\bigoplus a=b
\]
- encode数组长度为n-1,则perm数组长度为n
perm=[1,2,3,......,n]的排列
- 假设perm=[A,B,C,D,E],encode=[F,G,H,I],n为奇数
\(A\bigoplus B=F \ \ \ B\bigoplus C=G\ \ \ C\bigoplus D=H \ \ \ D\bigoplus E=I\)
\(A\bigoplus B\bigoplus C\bigoplus D\bigoplus E=A\bigoplus (B\bigoplus C)\bigoplus (D\bigoplus E)\)
\(encode=[F,G,H,I]=[A\bigoplus B,B\bigoplus C,C\bigoplus D,D\bigoplus E]\)
\(A=A\bigoplus (B\bigoplus C)\bigoplus (D\bigoplus E)\ \ \bigoplus \ \ \ (B\bigoplus C)\bigoplus (D\bigoplus E)\)
因为n为奇数,所以可以从1开始,后每面两个元素的异或值,可以求出perm数组的第一个元素,剩余步骤同leetcode1720一致
代码
class Solution:
def decode(self, encoded):
ABCDE=0
n=len(encoded)+1
for i in range(1,n+1):
ABCDE^=i
i=1
BCDE=0
while i<n:
BCDE^=encoded[i]
i+=2
perm=[0]*n
perm[0]=ABCDE^BCDE
for i in range(1,n):
perm[i]=perm[i-1]^encoded[i-1]
return perm