[LeetCode] 1442. Count Triplets That Can Form Two Arrays of Equal XOR

Given an array of integers arr.

We want to select three indices ij 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 (ij 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: 10

Example 3:

Input: arr = [2,3]
Output: 0

Example 4:

Input: arr = [1,3,5,7,9]
Output: 3

Example 5:

Input: arr = [7,11,12,9,5,2,7,17,22]
Output: 8

Constraints:

  • 1 <= arr.length <= 300
  • 1 <= arr[i] <= 10^8

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

给你一个整数数组 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) 的数目。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是位运算。既然 a 和 b 都是位运算的结果,而且a == b所以根据XOR的性质我们可以得出 a ^ b = 0 的结论,因为两数相同异或为0,这个结论是可以被反推的。所以这个题是在找是否能满足a ^ b = 0的三元组。同时因为 a 和 b 是由很多数字互相异或 XOR 组成的,XOR 操作又是有结合律的,比如(a ^ b) ^ c = a ^ (b ^ c)。所以一旦发现有一段下标从 a 到 c 的数字 XOR 的结果为0,中间 b 的位置其实可以随便放,那么就有 c - a 种可能了。

时间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 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12873944.html