- 解码异或后的排列
我的解决方案`
package xortest;
public class XorTest {
public static void main(String[] args) {
XorTest xorTest = new XorTest();
int[] perm = xorTest.decode(new int[]{6,5,4,6});
for (int i = 0; i < perm.length; i++) {
Object o = perm[i];
System.out.print(o+" ");
}
}
public int[] decode(int[] encode){
int decodeLength = encode.length +1; //decode数组的长度需为encode数组长度+1
int[] perm = new int[decodeLength];
int output = 0;
for (int i = 1; i <= decodeLength; i++) { //如果encode长度为4,那么decode的长度就为5,数组基本元素为1,2,3,4,5;
output ^=i;
}
int odd = 0;
for (int i = 1; i <encode.length ; i+=2) { //如果encode长度为4,那么奇数位为1,3
odd^=encode[i]; //奇数位元素进行异或;
}
perm[0] = output^odd; //得出perm首位的元素,由于perm[0]^perm[1] = encodep[0] 、perm[1]^perm[2] = encodep[1]...,
//所以 perm[1] = encode[0]^perm[0],perm[2] = encodep[1]^perm[1]...
for (int i = 1; i < perm.length; i++) {
perm[i] = encode[i-1]^perm[i-1];
}
return perm;
}
}
[原题链接(https://leetcode-cn.com/problems/decode-xored-permutation/)