给你一个整数数组 arr 。
现需要从数组中取三个下标 i、j 和 k ,其中 (0 <= i < j <= k < arr.length) 。
a 和 b 定义如下:
a = arr[i] ^ arr[i + 1] ^ … ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ … ^ arr[k]
注意:^ 表示 按位异或 操作。
请返回能够令 a == b 成立的三元组 (i, j , k) 的数目。
示例 1:
输入:arr = [2,3,1,6,7]
输出:4
解释:满足题意的三元组分别是 (0,1,2), (0,2,2), (2,3,4) 以及 (2,4,4)
代码
class Solution {
public int countTriplets(int[] arr) {
int n=arr.length,res=0;
int [] temp=new int[n];
temp[0]=arr[0];
for(int i=1;i<n;i++)//生成前缀数组
{
temp[i]=arr[i]^temp[i-1];
if(temp[i]==0)//区间内出现a==b的情况,才能导致区间xor为0
for(int j=i-1;j>=0;j--)
if(temp[j]==(temp[j]^temp[i]))
res++;
}
for(int i=1;i<n;i++)//遍历子数组
for(int j=i+1;j<n;j++)
{
if((temp[i-1]^temp[j])==0)
for(int k=j-1;k>=i;k--)
if((temp[k]^temp[i-1])==(temp[k]^temp[j]))
res++;
}
return res;
}
}