对于leetcode1310:子数组异或查询
详情题目查看:
https://leetcode-cn.com/problems/xor-queries-of-a-subarray/
官方的题解也够明了:
https://leetcode-cn.com/problems/xor-queries-of-a-subarray/solution/zi-shu-zu-yi-huo-cha-xun-by-leetcode-solution/
对于异或小小解释下:
异或就是对n个数的二进制对应位的1的个数进行统计,是奇数个就等于1,偶数个就等于零。
1 xor 1 = 0 , 0 xor 0 =0 ,1 xor 0 = 0
数组中元素的二进制表示形式是:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
则:
这里补充更详细一点对于代码的解释:
class Solution {
public int[] xorQueries(int[] arr, int[][] queries) {
int n = arr.length;
int[] xors = new int[n + 1];
// xors[0]赋初值
xors[0] = 0;
for (int i = 0; i < n; i++) {
// xors[i+1] 存储的值是 arr[0] xor .... xor arr[i]的值
xors[i + 1] = xors[i] ^ arr[i];
}
int m = queries.length;
int[] ans = new int[m];
for (int i = 0; i < m; i++) {
// queries[i][0]是第i个查询的左值,queries[i][1]是第i个查询的右值
ans[i] = xors[queries[i][0]] ^ xors[queries[i][1] + 1];
}
return ans;
}
}