原题链接:
https://leetcode.cn/problems/decode-xored-array/
解题思路:
-
异或有如下性质:
a ^ a = 0
a ^ 0 = a
a ^ b = b ^ a
-
根据题意,已知
encoded[i - 1] = arr[i - 1] ^ arr[i]
,可以做如下转换:encoded[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]为firstlet arr = new Array(encoded.length + 1)arr[0] = firstfor (let i = 1; i < arr.length; i++) {// 根据异或的性质,计算arr的每个值arr[i] = arr[i - 1] ^ encoded[i - 1]}return arr
};