返回介绍

solution / 1400-1499 / 1442.Count Triplets That Can Form Two Arrays of Equal XOR / README_EN

发布于 2024-06-17 01:03:19 字数 3692 浏览 0 评论 0 收藏 0

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

中文文档

Description

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: 10

 

Constraints:

  • 1 <= arr.length <= 300
  • 1 <= arr[i] <= 108

Solutions

Solution 1

class Solution:
  def countTriplets(self, arr: List[int]) -> int:
    n = len(arr)
    pre = [0] * (n + 1)
    for i in range(n):
      pre[i + 1] = pre[i] ^ arr[i]
    ans = 0
    for i in range(n - 1):
      for j in range(i + 1, n):
        for k in range(j, n):
          a, b = pre[j] ^ pre[i], pre[k + 1] ^ pre[j]
          if a == b:
            ans += 1
    return ans
class Solution {
  public int countTriplets(int[] arr) {
    int n = arr.length;
    int[] pre = new int[n + 1];
    for (int i = 0; i < n; ++i) {
      pre[i + 1] = pre[i] ^ arr[i];
    }
    int ans = 0;
    for (int i = 0; i < n - 1; ++i) {
      for (int j = i + 1; j < n; ++j) {
        for (int k = j; k < n; ++k) {
          int a = pre[j] ^ pre[i];
          int b = pre[k + 1] ^ pre[j];
          if (a == b) {
            ++ans;
          }
        }
      }
    }
    return ans;
  }
}
class Solution {
public:
  int countTriplets(vector<int>& arr) {
    int n = arr.size();
    vector<int> pre(n + 1);
    for (int i = 0; i < n; ++i) pre[i + 1] = pre[i] ^ arr[i];
    int ans = 0;
    for (int i = 0; i < n - 1; ++i) {
      for (int j = i + 1; j < n; ++j) {
        for (int k = j; k < n; ++k) {
          int a = pre[j] ^ pre[i], b = pre[k + 1] ^ pre[j];
          if (a == b) ++ans;
        }
      }
    }
    return ans;
  }
};
func countTriplets(arr []int) int {
  n := len(arr)
  pre := make([]int, n+1)
  for i := 0; i < n; i++ {
    pre[i+1] = pre[i] ^ arr[i]
  }
  ans := 0
  for i := 0; i < n-1; i++ {
    for j := i + 1; j < n; j++ {
      for k := j; k < n; k++ {
        a, b := pre[j]^pre[i], pre[k+1]^pre[j]
        if a == b {
          ans++
        }
      }
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文