原题链接:
https://leetcode.cn/problems/decode-xored-array/
解题思路:
-
异或有如下性质:文章来源:https://uudwc.com/A/BvjAX
a ^ a = 0
a ^ 0 = a
a ^ b = b ^ a
-
根据题意,已知
encoded[i - 1] = arr[i - 1] ^ arr[i]
,可以做如下转换:文章来源地址https://uudwc.com/A/BvjAXencoded[i - 1] ^ arr[i - 1] = arr[i - 1] ^ arr[i] ^ arr[i - 1]
encoded[i - 1] ^ arr[i - 1] = arr[i] ^ 0
encoded[i - 1] ^ arr[i - 1] = arr[i]
/**
* @param {number[]} encoded
* @param {number} first
* @return {number[]}
*/
var decode = function (encoded, first) {
// 创建数组缓存最终结果,长度为encoded.length + 1,已知result[0]为first
let arr = new Array(encoded.length + 1)
arr[0] = first
for (let i = 1; i < arr.length; i++) {
// 根据异或的性质,计算arr的每个值
arr[i] = arr[i - 1] ^ encoded[i - 1]
}
return arr
};