1720. 解码异或后的数组
未知 整数数组 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]
提示:
2 <= n <= 104
encoded.length == n - 1
0 <= encoded[i] <= 105
0 <= first <= 105
原站题解
rust 解法, 执行用时: 8 ms, 内存消耗: 2 MB, 提交时间: 2023-09-12 16:11:16
impl Solution { pub fn decode(encoded: Vec<i32>, mut first: i32) -> Vec<i32> { let mut ret = vec![first]; for n in encoded { first ^= n; ret.push(first); } ret } } /* impl Solution { pub fn decode(encoded: Vec<i32>, first: i32) -> Vec<i32> { let len = encoded.len(); let mut arr = vec![first; len + 1]; for i in 0..len { arr[i + 1] = encoded[i] ^ arr[i]; } arr } } */
javascript 解法, 执行用时: 88 ms, 内存消耗: 47.3 MB, 提交时间: 2023-09-12 16:09:03
/** * @param {number[]} encoded * @param {number} first * @return {number[]} */ var decode = function(encoded, first) { const n = encoded.length + 1; const arr = new Array(n).fill(0); arr[0] = first; for (let i = 1; i < n; i++) { arr[i] = arr[i - 1] ^ encoded[i - 1]; } return arr; };
cpp 解法, 执行用时: 28 ms, 内存消耗: 24.2 MB, 提交时间: 2023-09-12 16:08:36
class Solution { public: vector<int> decode(vector<int>& encoded, int first) { int n = encoded.size() + 1; vector<int> arr(n); arr[0] = first; for (int i = 1; i < n; i++) { arr[i] = arr[i - 1] ^ encoded[i - 1]; } return arr; } };
java 解法, 执行用时: 2 ms, 内存消耗: 44 MB, 提交时间: 2023-09-12 16:06:05
class Solution { public int[] decode(int[] encoded, int first) { int n = encoded.length; int[] ans = new int[n+1]; ans[0] = first; for ( int i = 0; i < n ; ++i ) { int d = encoded[i] ^ ans[i]; ans[i+1] = d; } return ans; } }
php 解法, 执行用时: 80 ms, 内存消耗: 21.9 MB, 提交时间: 2023-09-12 16:04:13
class Solution { /** * @param Integer[] $encoded * @param Integer $first * @return Integer[] */ function decode($encoded, $first) { $n = count($encoded); $ans = array_fill(0, $n+1, 0); $ans[0] = $first; foreach ( $encoded as $i => $e ) { $d = $e ^ $ans[$i]; $ans[$i+1] = $d; } return $ans; } }
python3 解法, 执行用时: 56 ms, 内存消耗: 17.8 MB, 提交时间: 2023-09-12 16:02:52
class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: n = len(encoded) ans = [0 for _ in range(n+1)] ans[0] = first for i, e in enumerate(encoded): d = e ^ ans[i] ans[i+1] = d return ans
golang 解法, 执行用时: 36 ms, 内存消耗: 6.8 MB, 提交时间: 2021-06-07 17:04:22
func decode(encoded []int, first int) []int { n := len(encoded) ans := make([]int, n+1) ans[0] = first for i, e := range encoded { d := e ^ ans[i] ans[i+1] = d } return ans }