leetcode1442. 形成两个异或相等数组的三元组数目

给你一个整数数组 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;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值