leetcode1442. 形成两个异或相等数组的三元组数目
生活随笔
收集整理的這篇文章主要介紹了
leetcode1442. 形成两个异或相等数组的三元组数目
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給你一個整數(shù)數(shù)組 arr 。
現(xiàn)需要從數(shù)組中取三個下標 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) 的數(shù)目。
示例 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++)//生成前綴數(shù)組{temp[i]=arr[i]^temp[i-1];if(temp[i]==0)//區(qū)間內出現(xiàn)a==b的情況,才能導致區(qū)間xor為0for(int j=i-1;j>=0;j--)if(temp[j]==(temp[j]^temp[i]))res++;}for(int i=1;i<n;i++)//遍歷子數(shù)組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;} }總結
以上是生活随笔為你收集整理的leetcode1442. 形成两个异或相等数组的三元组数目的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode657. 机器人能否返回
- 下一篇: 梦到走冰路是什么意思