chencl1986 / Blog

Welcome to lee's blog.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LeetCode题解:1720. 解码异或后的数组,异或,JavaScript,详细注释

chencl1986 opened this issue · comments

原题链接:
https://leetcode.cn/problems/decode-xored-array/

解题思路:

  1. 异或有如下性质:

    • a ^ a = 0
    • a ^ 0 = a
    • a ^ b = b ^ a
  2. 根据题意,已知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]为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
};