/** * @param {number[]} encoded * @return {number[]} */ var decode = function(encoded) { let n = encoded.length+1; let total = 0; for(let i=1;i<=n;i++){ total ^=i; } let odd = 0; for(let j =1;j<n-1;j+=2){ odd ^=encoded[j]; } let perm = new Array(n).fill(0); perm[0] = total ^ odd; for(let k=0;k<n-1;k++){ perm[k+1] = perm[k] ^ encoded[k]; } return perm; }; let encoded = [3,1] console.log(encoded, decode(encoded)) encoded = [6,5,4,6] console.log(encoded, decode(encoded))
// 示例 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 < 105 // n 是奇数。 // encoded.length == n - 1