LeetCode 2433.找出前缀异或的原始数组

给你一个长度为 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

根据题意,我们得到以下公式:

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

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

如果a ^ b = c,则b = a ^ c,a = b ^ c,因此arr[i] = pref[i] ^ pref[i - 1],直接模拟即可:

cpp 复制代码
class Solution {
public:
    vector<int> findArray(vector<int>& pref) { 
        vector <int> res(1, pref[0]);
        for (int i = 1; i < pref.size(); ++i)
        {
            res.push_back(pref[i - 1] ^ pref[i]);
        }

        return res;
    }
};

如果pref的长度为n,则此算法时间复杂度为O(n),空间复杂度为O(1)。

相关推荐
汀、人工智能2 分钟前
07 - 字典dict:哈希表的Python实现
数据结构·算法·数据库架构·哈希表的python实现
oG99bh7CK8 分钟前
高光谱成像基础(六)滤波匹配 MF
人工智能·算法·目标跟踪
汀、人工智能8 分钟前
04 - 控制流:if/for/while
数据结构·算法·链表·数据库架构··if/for/while
努力学习的小廉29 分钟前
我爱学算法之——动态规划(四)
算法·动态规划
北顾笙9801 小时前
day15-数据结构力扣
数据结构·算法·leetcode
AI成长日志1 小时前
【GitHub开源项目专栏】黑客松项目架构模式解析:微服务、事件驱动与Serverless实战
算法
人道领域1 小时前
【LeetCode刷题日记:24】两两交换链表
算法·leetcode·链表
北顾笙9801 小时前
day16-数据结构力扣
数据结构·算法·leetcode
AI成长日志1 小时前
【算法学习专栏】动态规划基础·简单三题精讲(70.爬楼梯、118.杨辉三角、121.买卖股票的最佳时机)
学习·算法·动态规划
wsoz2 小时前
Leetcode子串-day4
c++·算法·leetcode