Skip to content

Latest commit

 

History

History
138 lines (88 loc) · 2.98 KB

File metadata and controls

138 lines (88 loc) · 2.98 KB

中文文档

Description

Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries.

 

Example 1:

Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]

Output: [2,7,14,8] 

Explanation: 

The binary representation of the elements in the array are:

1 = 0001 

3 = 0011 

4 = 0100 

8 = 1000 

The XOR values for queries are:

[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

Example 2:

Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]

Output: [8,0,4,4]

 

Constraints:

  • 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

Solutions

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;
};

...