1734. 解码异或后的排列
给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。
它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。
给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。
示例 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
题解:
首先要知道的是异或运算有一个重要的性质,即具有可逆性。
即对于1,2,3三个数,1和2异或后再和3异或与1先和3异或再跟2异或是一样的;
因此合理利用其可逆性我们就可以像leetcode.1720. 解码异或后的数组—位运算一样进行解题,但是我们发现还缺少了一个first,即perm的第一个元素是要知道的因此我们需要先求出perm的第一个元素。
即我们观察题目得知,题目专门告诉我们perm是有奇数个元素,那么我们就可以知道encoded是有偶数个元素;
并且由于此为排列,由排列的性质我们可以知道perm内部的元素为1到encoded+1 的整数的排列,因此我们可以求出perm所有元素的异或结果tar1;
并且由前面我们得到的encoded数组有偶数个元素,以及encoded数组每一个元素得到的过程我们可以知道,将encoded数组所有下标为奇数的元素进行异或,即相当于将perm的除了第一个元素的所有元素进行异或,因此我们可以得到tar2;
最后我们发现tar1 与 tar2 进行异或后即为我们想要的first,即perm[0],剩下的过程同leetcode.1720. 解码异或后的数组—位运算。
代码(Java):
class Solution {
public int[] decode(int[] encoded) {
int[] res = new int[encoded.length+1];
int tar1 = 0;
int tar2 = 0;
for(int i=1;i<=encoded.length+1;i++){
tar1 ^= i;
}
for(int i=1;i<encoded.length;i+=2){
tar2 ^= encoded[i];
}
res[0] = tar2^tar1;
for(int i=1;i<encoded.length+1;i++){
res[i] = res[i-1] ^ encoded[i-1];
}
return res;
}
}
代码(C):
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* decode(int* encoded, int encodedSize, int* returnSize){
int*res = (int*)malloc(sizeof(int)*(encodedSize+1));
int tar1 = 0;
int tar2 = 0;
for(int i=1;i<=encodedSize+1;i++)
{
tar1 ^= i;
}
for(int i=1;i<encodedSize;i+=2)
{
tar2 ^= encoded[i];
}
res[0] = tar2^tar1;
for(int i=1;i<encodedSize+1;i++)
{
res[i] = res[i-1] ^ encoded[i-1];
}
*returnSize = encodedSize+1;
return res;
}