标签:res fine arrays turn ant code htm += bsp
Given an array of integers arr
.
We want to select three indices i
, j
and k
where (0 <= i < j <= k < arr.length)
.
Let‘s define a
and b
as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i
, j
and k
) Where a == b
.
Example 1:
Input: arr = [2,3,1,6,7] Output: 4 Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)Example 2:
Input: arr = [1,1,1,1,1] Output: 10Example 3:
Input: arr = [2,3] Output: 0Example 4:
Input: arr = [1,3,5,7,9] Output: 3Example 5:
Input: arr = [7,11,12,9,5,2,7,17,22] Output: 8
Constraints:
1 <= arr.length <= 300
1 <= arr[i] <= 10^8
形成两个异或相等数组的三元组数目。题意是请你返回一个三元组(i, j, k),这三个数字都是数组里面的index,请你返回三元组使得a == b并且a, b满足
思路是位运算。既然a和b的得出都是位运算,而且a == b所以得出a ^ b = 0的结论,因为两数相同异或为0,这个结论是可以被反推的,所以这个题是在找是否能满足a ^ b = 0的三元组。所以可以试着从i开始一路往后做异或操作,如果找到某一个坐标k使得数字i到k的部分异或为0,那么这个中间j的位置就有k - i种可能了。
时间O(n^2)
空间O(1)
Java实现
1 class Solution { 2 public int countTriplets(int[] arr) { 3 int len = arr.length; 4 if (len < 2) { 5 return 0; 6 } 7 int res = 0; 8 for (int i = 0; i < len; i++) { 9 int temp = arr[i]; 10 for (int j = i + 1; j < len; j++) { 11 temp = temp ^ arr[j]; 12 if (temp == 0) { 13 res += j - i; 14 } 15 } 16 } 17 return res; 18 } 19 }
[LeetCode] 1442. Count Triplets That Can Form Two Arrays of Equal XOR
标签:res fine arrays turn ant code htm += bsp
原文地址:https://www.cnblogs.com/cnoodle/p/12873944.html