Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

解码异或后的数组 #254

Open
louzhedong opened this issue May 6, 2021 · 0 comments
Open

解码异或后的数组 #254

louzhedong opened this issue May 6, 2021 · 0 comments

Comments

@louzhedong
Copy link
Owner

louzhedong commented May 6, 2021

习题

未知 整数数组 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 。可以证明答案存在并且是唯一的。

示例 1:

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

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

思考

本题更像一道数学题目

根据题目的规则,我们首先需要了解异或有哪些特性

  1. 相同位置上,如果两个数值相同,结果为0
  2. 相同位置上,如果两个数值不相同,结果为1
  3. 任何数值与0异或,结果为数值本身
  4. 异或满足交换律

根据题目给的条件来进行推导

encoded[i] = arr[i - 1] XOR arr[i]

将等式两边同时异或arr[i - 1]

encoded[i] XOR arr[i - 1] = arr[i - 1] XOR arr[i] XOR arr[i - 1]

运用公式4,交换右边

encoded[i] XOR arr[i - 1] = arr[i] XOR arr[i - 1] XOR arr[i - 1]

运用公式1

encoded[i] XOR arr[i - 1] = arr[i] XOR 0

运用公式3

encoded[i] XOR arr[i - 1] = arr[i]

所以我们只要顺序遍历一遍encoded数组,就能计算出原数组

解答

javascript

var decode = function(encoded, first) {
    var res = [first];
    while(encoded.length > 0) {
        var second = encoded.shift();
        var next = first ^ second;
        res.push(next);
        first = next;
    }
    return res;
};

go

func decode(encoded []int, first int) []int {
    res := make([]int, 0)
    res = append(res, first)

    for _, second := range encoded {
        var next int = first ^ second
        res = append(res, next)
        first = next
    }
    return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant