[LeetCode] 2433. Find The Original Array of Prefix Xor

发布时间 2023-09-05 04:20:19作者: CNoodle

You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:

  • pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].

Note that ^ denotes the bitwise-xor operation.

It can be proven that the answer is unique.

Example 1:

Input: pref = [5,2,0,3,1]
Output: [5,7,2,3,2]
Explanation: From the array [5,7,2,3,2] we have the following:
- 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.

Example 2:

Input: pref = [13]
Output: [13]
Explanation: We have pref[0] = arr[0] = 13.

Constraints:

  • 1 <= pref.length <= 105
  • 0 <= pref[i] <= 106

找出前缀异或的原始数组。

给你一个长度为 n 的 整数 数组 pref 。找出并返回满足下述条件且长度为 n 的数组 arr :

  • pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].

注意 ^ 表示 按位异或(bitwise-xor)运算。

可以证明答案是 唯一 的。

思路是利用 XOR 运算的交换律来解决。XOR 运算,如果 a ^ b = c,那么就有 b ^ c = a 和 a ^ c = b。题目给的是一些数字的 XOR 运算的前缀和数组,那么我们可以通过这个交换律把原数组反推出来。我们仔细跑一下例子一,
pref = [5,2,0,3,1]

注意看 pref 的第一个元素就是原数组第一个元素 5,我们追踪一下此时原数组的恢复情况,nums = [5]

pref 数组里第二个元素 = 2,这个 2 是怎么来的呢,应该是原数组里某个数字与 5 做 XOR 操作得来的,即 5 ^ X = 2。根据交换律,这个数字 X = 2 ^ 5 = 7,nums = [5, 7]

pref 数组里第三个元素 = 0,这个 0 是怎么来的呢,应该是原数组里某个数字与上一个前缀和的结果 2 做 XOR 操作得来的,即 2 ^ X = 0,反推回去,X = 0 ^ 2 = 2,nums = [5, 7, 2]

pref 数组里第四个元素 = 3,这个 3 是怎么来的呢,应该是原数组里某个数字与上一个前缀和的结果 0 做 XOR 操作得来的,即 0 ^ X = 3,反推回去,X = 0 ^ 3 = 3,nums = [5, 7, 2, 3]

pref 数组里第五个元素 = 1,这个 1 是怎么来的呢,应该是原数组里某个数字与上一个前缀和的结果 3 做 XOR 操作得来的,即 3 ^ X = 1,反推回去,X = 1 ^ 3 = 2,nums = [5, 7, 2, 3, 2]

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int[] findArray(int[] pref) {
 3         int n = pref.length;
 4         int[] res = new int[n];
 5         res[0] = pref[0];
 6         for (int i = 1; i < n; i++) {
 7             res[i] = pref[i - 1] ^ pref[i];
 8         }
 9         return res;
10     }
11 }

 

LeetCode 题目总结