comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
中等 |
2024 |
第 44 场双周赛 Q3 |
|
给你一个整数数组 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
我们注意到,数组
时间复杂度
class Solution:
def decode(self, encoded: List[int]) -> List[int]:
n = len(encoded) + 1
a = b = 0
for i in range(0, n - 1, 2):
a ^= encoded[i]
for i in range(1, n + 1):
b ^= i
perm = [0] * n
perm[-1] = a ^ b
for i in range(n - 2, -1, -1):
perm[i] = encoded[i] ^ perm[i + 1]
return perm
class Solution {
public int[] decode(int[] encoded) {
int n = encoded.length + 1;
int a = 0, b = 0;
for (int i = 0; i < n - 1; i += 2) {
a ^= encoded[i];
}
for (int i = 1; i <= n; ++i) {
b ^= i;
}
int[] perm = new int[n];
perm[n - 1] = a ^ b;
for (int i = n - 2; i >= 0; --i) {
perm[i] = encoded[i] ^ perm[i + 1];
}
return perm;
}
}
class Solution {
public:
vector<int> decode(vector<int>& encoded) {
int n = encoded.size() + 1;
int a = 0, b = 0;
for (int i = 0; i < n - 1; i += 2) {
a ^= encoded[i];
}
for (int i = 1; i <= n; ++i) {
b ^= i;
}
vector<int> perm(n);
perm[n - 1] = a ^ b;
for (int i = n - 2; ~i; --i) {
perm[i] = encoded[i] ^ perm[i + 1];
}
return perm;
}
};
func decode(encoded []int) []int {
n := len(encoded) + 1
a, b := 0, 0
for i := 0; i < n-1; i += 2 {
a ^= encoded[i]
}
for i := 1; i <= n; i++ {
b ^= i
}
perm := make([]int, n)
perm[n-1] = a ^ b
for i := n - 2; i >= 0; i-- {
perm[i] = encoded[i] ^ perm[i+1]
}
return perm
}