# 【js】Leetcode每日一题-子数组异或查询

## 【题目描述】

输入：arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]

1 = 0001
3 = 0011
4 = 0100
8 = 1000

[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


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



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


## 【分析】

### 代码：

/**
* @param {number[]} arr
* @param {number[][]} queries
* @return {number[]}
*/
var xorQueries = function(arr, queries) {
const n = arr.length;
const result = new Array(n+1).fill(0); //n+1方便后面直接预处理以及计算结果
for(let i=1;i<=n;i++){
result[i] = result[i-1] ^ arr[i-1];
}
const newArr = new Array(queries.length).fill(0);
for(let i=0;i<queries.length;i++){
newArr[i] = result[queries[i][0]] ^ result[queries[i][1]+1];
}
return newArr;
};


/**
* @param {number[]} arr
* @param {number[][]} queries
* @return {number[]}
*/
var xorQueries = function(arr, queries) {
const n = arr.length;
const result = new Array(n+1).fill(0);
for(let i=1;i<=n;i++){
result[i] = result[i-1] ^ arr[i-1];
}
for(let i=0;i<queries.length;i++){
queries[i] = result[queries[i][0]] ^ result[queries[i][1]+1];
}
return queries;
};

posted @ 2021-05-12 00:31  kernel_developer  阅读(41)  评论(0编辑  收藏  举报