We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
未知 整数数组 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]
未知 整数数组 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]
本题更像一道数学题目
根据题目的规则,我们首先需要了解异或有哪些特性
根据题目给的条件来进行推导
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 }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思考
本题更像一道数学题目
根据题目的规则,我们首先需要了解异或有哪些特性
根据题目给的条件来进行推导
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
go
The text was updated successfully, but these errors were encountered: