Skip to content

Latest commit

 

History

History
125 lines (94 loc) · 3.55 KB

File metadata and controls

125 lines (94 loc) · 3.55 KB

English Version

题目描述

有一个正整数数组 arr,现给你一个对应的查询数组 queries,其中 queries[i] = [Li, Ri]

对于每个查询 i,请你计算从 Li 到 Ri 的 XOR 值(即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri])作为本次查询的结果。

并返回一个包含给定查询 queries 所有结果的数组。

 

示例 1:

输入:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
输出:[2,7,14,8] 
解释:
数组中元素的二进制表示形式是:
1 = 0001 
3 = 0011 
4 = 0100 
8 = 1000 
查询的 XOR 值为:
[0,1] = 1 xor 3 = 2 
[1,2] = 3 xor 4 = 7 
[0,3] = 1 xor 3 xor 4 xor 8 = 14 
[3,3] = 8

示例 2:

输入:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
输出:[8,0,4,4]

 

提示:

  • 1 <= arr.length <= 3 * 10^4
  • 1 <= arr[i] <= 10^9
  • 1 <= queries.length <= 3 * 10^4
  • queries[i].length == 2
  • 0 <= queries[i][0] <= queries[i][1] < arr.length

解法

由于 A ^ B = C => A ^ A ^ B = A ^ C => B = A ^ C。因此,我们求解 arr[l] ^ ... ^ arr[r],可以转换为求解 arr[0] ^ ... ^ arr[l - 1] ^ arr[0] ^ ... ^ ... ^ arr[r]

所以,我们先求解前缀异或,再进行两数异或即可求得每一个 query 的结果。

Python3

class Solution:
    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
        pre_xor = [0] * (len(arr) + 1)
        for i in range(1, len(arr) + 1):
            pre_xor[i] = pre_xor[i - 1] ^ arr[i - 1]
        return [pre_xor[l] ^ pre_xor[r + 1] for l, r in queries]

Java

class Solution {
    public int[] xorQueries(int[] arr, int[][] queries) {
        int[] preXor = new int[arr.length + 1];
        for (int i = 1; i <= arr.length; ++i) {
            preXor[i] = preXor[i - 1] ^ arr[i - 1];
        }
        int[] res = new int[queries.length];
        for (int i = 0; i < queries.length; ++i) {
            int l = queries[i][0], r = queries[i][1];
            res[i] = preXor[l] ^ preXor[r + 1];
        }
        return res;
    }
}

JavaScript

/**
 * @param {number[]} arr
 * @param {number[][]} queries
 * @return {number[]}
 */
var xorQueries = function(arr, queries) {
    let n = arr.length;
    let xors = new Array(n + 1).fill(0);
    for (let i = 0; i < n; i++) {
        xors[i + 1] = xors[i] ^ arr[i]; 
    }
    let res = [];
    for (let query of queries) {
        let [start, end] = query;
        res.push(xors[start] ^ xors[end + 1]);
    }
    return res;
};

...