力扣 1720. 解码异或后的数组

题目说明

  • 未知 整数数组 arrn 个非负整数组成。

    经编码后变为长度为 n - 1 的另一个整数数组 encoded ,其中 encoded[i] = arr[i] XOR arr[i + 1] 。例如,arr = [1,0,2,1] 经编码后得到 encoded = [1,2,3]

    给你编码后的数组 encoded 和原数组 arr 的第一个元素 firstarr[0])。

    请解码返回原数组 arr 。可以证明答案存在并且是唯一的。

  • 提示:
    • 2 <= n <= 10^4
    • encoded.length == n - 1
    • 0 <= encoded[i] <= 10^5
    • 0 <= first <= 10^5

示例

例 1:

1
2
3
输入:encoded = [1,2,3], first = 1
输出:[1,0,2,1]
解释:若 arr = [1,0,2,1] ,那么 first = 1 且 encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]

例 2:

1
2
输入:encoded = [6,2,7,3], first = 4
输出:[4,2,0,7,4]

笔者理解

此题是一道位运算算法问题,在力扣题库中被定义为简单题。

解法

当笔者阅读完此题后,发现此题运用异或的运算性质或者直接还原的方法进行求解,让我们来看看具体如何实现的吧。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public int[] decode(int[] encoded, int first) {
int n = encoded.length;
int[] result = new int [n + 1];
result[0] = first;
for (int i = 1; i < n + 1; i++) {
// 异或还原操作
// result[i] = count(result[i - 1], encoded[i - 1]);

// 异或性质 a^b = c; a^b^b = a; 所以c^b = a
result[i] = result[i - 1] ^ encoded[i - 1];
}
return result;
}

public int count(int source, int export) {
// a^0 = a
if (source == export) {
return 0;
}
// 0^a = a
if (source == 0) {
return export;
}
// a^a = 0
if (export == 0) {
return source;
}

int num = 0;

int times = 0;

int temp1, temp2;

// 逐位进行还原
while (source != 0 || export != 0) {
temp1 = export % 2;
temp2 = source % 2;
num += Math.abs(temp1 - temp2) * Math.pow(2, times++);
export /= 2;
source /= 2;
}

return num;
}
}

时间和空间效率都还行,可见此解法还比较适合此题;

image.png

总结

本题是今天的每日一题,难度是为简单,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。