Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-05-30 21:05:49
1442. Count Triplets That Can Form Two Arrays of Equal XOR
有一個整數array
找出三個index:i、j、k
a=arr[i]^arr[i+1^...^arr[j-1]
b=arr[j]^arr[j+1]^...^arr[k]
然後a==b
思路
a==b -> b^a==b^b -> b^a ==0
用兩層for loop找出subarray裡面所有元素XOR的結果為零
a^b==0 -> a^a^b==a^0 -> b==a
這個subarray中的任意兩個subarray都可以滿足題目需求
golang code :
func countTriplets(arr []int) int {
n,ans:=len(arr),0
for i:=0;i<n;i++{
sum:=arr[i]
for j:=i+1;j<n;j++{
sum^=arr[j]
if sum==0{
ans+=j-i
}
}
}
return ans
}
作者: sustainer123 (caster)   2024-05-30 21:17:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com