中文描述:
给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。
它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。
给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。
题目描述:
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.
It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].
Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.
Example 1:
Input: encoded = [3,1]
Output: [1,2,3]
Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]
Example 2:
Input: encoded = [6,5,4,6]
Output: [2,4,1,5,3]
Constraints:
3 <= n < 105
n is odd.
encoded.length == n - 1
Time complexity:
O
O
O(
N
N
N)
Space complexity:
O
O
O(
N
N
N)
位运算 XOR:
根据异或位运算的性质:
- 归零律:a ⊕ a = 0
- 恒等律:a ⊕ 0 = a
- 自反律:a ⊕ b ⊕ a = b.
注意到原perm数组的长度位奇数,则我们可以把除第一个数 perm[0] 以外的数两两配对,找出它们的异或和 计为 xsum, 即encoded 数组中index 为奇数的异或和。
e.g encoded = [6,5,4,6], perm = [2,4,1,5,3]。 除了perm[0] = 2 以外:
perm[1] ⊕ perm[2] = 4 ⊕ 1 = 5 = encoded[1];
perm[3] ⊕ perm[4] = 5 ⊕ 3 = 6 = encoded[3].
xsum = 5 ⊕ 6 = 3
再求出原perm数组中n个数的异或和 e.g: sum = 1 ⊕ 2 ⊕ 3 ⊕ 4 ⊕ 5 = 1.
则根据3自反律第一个数 perm[0] = sum ⊕ xsum = 1。
得到第一个数后,我们可以根据自反律,从左往右遍历啊 encoded 得到原数组。
已知 a = perm[i],c = encoded[i] = perm[i] ⊕ perm[i + 1] . 我们已知 a 和 c 则:
a⊕c = perm[i] ⊕ perm[i] ⊕ perm[i + 1] = perm[i + 1].
class Solution {
public int[] decode(int[] encoded) {
int n = encoded.length+1;
int[] res = new int[n];
int sum = 0;
for(int i = 1; i <= n; i++){
sum ^= i;
}
int num1 = sum;
for(int i = 1; i < n-1; i+=2){
num1 ^= encoded[i];
}
res[0] = num1;
for(int i = 0; i < n-1; i++){
res[i+1] = res[i]^encoded[i];
}
return res;
}
}