美文网首页
算法练习20:解码异或后的数组(leetcode 1720)

算法练习20:解码异或后的数组(leetcode 1720)

作者: miao8862 | 来源:发表于2021-05-07 19:54 被阅读0次

题目:

未知 整数数组 arr 由 n 个非负整数组成。

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

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

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

输入: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]

解法

利用异或的原理:

  • a ^ a = 0
  • a ^ 0 = a

所以 a ^ x = y
=>
a ^ a ^ x = a ^ y
=>
0 ^ x = a ^ y
=>
x = a ^ y

异或实现

var decode = function(encoded, first) {
    let res = [first]
    for(let i = 0; i < encoded.length; i++) {
        res.push(encoded[i]^res[i])
    }
    return res
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n),因为新建一个结果存储

优化空间

var decode = function(encoded, first) {
    encoded.unshift(first)
    for(let i = 1; i < encoded.length; i++) {
        encoded[i] = encoded[i]^encoded[i-1]
    }
    return encoded
};

使用原数组,只添加一个常量空间:

  • 时间:O(n)
  • 空间:O(1)
    虽然因为插入,多要遍历一次,所以时间复杂实际上是增加了,O(2n),但没到量级别,所以会被近似为O(n)

相关文章

网友评论

      本文标题:算法练习20:解码异或后的数组(leetcode 1720)

      本文链接:https://www.haomeiwen.com/subject/dvrrdltx.html