2433. 找出前缀异或的原始数组
来源第 314 场周赛 Q2难度中等分数1366
题目描述
给你一个长度为 n 的 整数 数组 pref 。找出并返回满足下述条件且长度为 n 的数组 arr :
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].
注意 ^ 表示 按位异或(bitwise-xor)运算。
可以证明答案是 唯一 的。
示例 1:
输入:pref = [5,2,0,3,1] 输出:[5,7,2,3,2] 解释:从数组 [5,7,2,3,2] 可以得到如下结果: - pref[0] = 5 - pref[1] = 5 ^ 7 = 2 - pref[2] = 5 ^ 7 ^ 2 = 0 - pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3 - pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1
示例 2:
输入:pref = [13] 输出:[13] 解释:pref[0] = arr[0] = 13
提示:
1 <= pref.length <= 1050 <= pref[i] <= 106
解法
方法一:位运算
思考
\(\textit{pref}[i]\) 是 \(\textit{arr}[0..i]\) 的异或前缀。异或满足 \(\textit{pref}[i]\oplus \textit{pref}[i-1]=\textit{arr}[i]\)(令 \(\textit{pref}[-1]=0\)),因此原数组由相邻前缀异或唯一确定。 \(n \le 10^5\),线性一遍即可。
根据题意,我们有式子一:
\[ \textit{pref}[i]=\textit{arr}[0] \oplus \textit{arr}[1] \oplus \cdots \oplus \textit{arr}[i] \]
所以,也就有式子二:
\[ \textit{pref}[i-1]=\textit{arr}[0] \oplus \textit{arr}[1] \oplus \cdots \oplus \textit{arr}[i-1] \]
我们将式子一二进行异或运算,得到:
\[ \textit{pref}[i] \oplus \textit{pref}[i-1]=\textit{arr}[i] \]
即答案数组的每一项都是前缀异或数组的相邻两项进行异或运算得到的。
时间复杂度 \(O(n)\),空间复杂度 \(O(1)\)。其中 \(n\) 为前缀异或数组的长度。
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |