LeetCode 题解工作台

找出前缀异或的原始数组

给你一个长度为 n 的 整数 数组 pref 。找出并返回满足下述条件且长度为 n 的数组 arr : pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i] . 注意 ^ 表示 按位异或 (bitwise-xor)运算。 可以证明答案是 唯一 的。 示例 1: 输入: p…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·结合·位运算·操作

bolt

答案摘要

根据题意,我们有式子一: $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 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 <= 105
  • 0 <= pref[i] <= 106
lightbulb

解题思路

方法一:位运算

根据题意,我们有式子一:

pref[i]=arr[0]arr[1]arr[i]pref[i]=arr[0] \oplus arr[1] \oplus \cdots \oplus arr[i]

所以,也就有式子二:

pref[i1]=arr[0]arr[1]arr[i1]pref[i-1]=arr[0] \oplus arr[1] \oplus \cdots \oplus arr[i-1]

我们将式子一二进行异或运算,得到:

pref[i]pref[i1]=arr[i]pref[i] \oplus pref[i-1]=arr[i]

即答案数组的每一项都是前缀异或数组的相邻两项进行异或运算得到的。

时间复杂度 O(n)O(n),其中 nn 为前缀异或数组的长度。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def findArray(self, pref: List[int]) -> List[int]:
        return [a ^ b for a, b in pairwise([0] + pref)]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate describe the properties of XOR and how it can be used to reverse the prefix array?

  • question_mark

    Do they understand the iterative nature of the problem and can they apply the XOR operation correctly?

  • question_mark

    Can they optimize the solution to handle large inputs efficiently?

warning

常见陷阱

外企场景
  • error

    Misunderstanding the XOR properties and attempting a more complex solution than necessary.

  • error

    Failing to handle edge cases where the array length is minimal or contains zeros.

  • error

    Overcomplicating the solution by introducing unnecessary operations or data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the prefix XOR array is given in reverse order? Can you adjust the approach?

  • arrow_right_alt

    What happens if the array size is much larger? How would you ensure your solution is still efficient?

  • arrow_right_alt

    Could a more complex data structure be used for a different variant of this problem?

help

常见问题

外企场景

找出前缀异或的原始数组题解:数组·结合·位运算·操作 | LeetCode #2433 中等