1.异或的特性
0 ^ a = a 恒等性
a ^ a = 0 归零性
a^b = b^a 交换律
a^b^c = a^(b^c) = (a^b)^c 结合率
a^b^a = b 自反
根据以上特性:解决
1720. 解码异或后的数组
1720.
已知 encode: AB(A^B), BC(B^C), CD(C^D)
已知 first :A
求B C D
B = A ^ AB
C = BC ^ B
D = CD ^ C
class Solution {
public int[] decode(int[] encoded, int first) {
int len = encoded.length;
int[] res = new int[len+1];
res[0] = first;
for(int i=1; i<=len; i++){
res[i] = encoded[i-1]^res[i-1];
}
return res;
}
}
1734.
已知 encoded AB BC CD DE
且perm 是 1-n的排列 因此可以计算出:ABCDE
通过 encoded -> BCDE,通过perm可以得到ABCDE,那么:BCDE^ABCDE = A
得到A之后 -> 转化为上面一题:
A^AB = B
B^BC = C
...
最后得到A B C D E
class Solution {
// 假设encoded: AB BC CD DE
// perm 即为A B C D E
// 根据perm ABCDE 和 encoded BCDE 推断出A
public int[] decode(int[] encoded) {
int[] perm = new int[encoded.length+1];
int permLength = perm.length;
// 分别存储 (ABCDE) (BC DE)
int permAll = 0, encodedAll = 0;
for(int i=0; i<permLength; i++){
permAll ^= (i+1);
if( (i&1) == 1){
encodedAll ^= encoded[i];
}
}
// 找到A
perm[0] = encodedAll^permAll;
// 根据 A找B 通过encoded AB BC CD DE
for(int i=1; i<perm.length; i++){
perm[i] = (perm[i-1]^encoded[i-1]);
}
return perm;
}
}