C++中統計可構成兩個異或值相等的陣列的三元組
假設我們有一個整數陣列arr。我們想要選擇三個索引i、j和k,其中(0 <= i < j <= k < N),N是陣列的大小。a和b的值如下:a = arr[i] XOR arr[i + 1] XOR ... XOR arr[j - 1] b = arr[j] XOR arr[j + 1] XOR ... XOR arr[k] 我們需要找到a等於b的三元組(i, j, k) 的數量。
因此,如果輸入是[2,3,1,6,7],則輸出將是4,因為三元組是(0,1,2)、(0,2,2)、(2,3,4)和(2,4,4)
為了解決這個問題,我們將遵循以下步驟:
ret := 0
n := arr的大小
for i := 1 to n-1 do −
定義一個map m
x1 := 0, x2 := 0
for j := i - 1 downto 0 do −
x1 := x1 XOR arr[j]
m[x1] := m[x1] + 1
for j := i to n-1 do −
x2 := x2 XOR arr[j]
ret := ret + m[x2]
return ret
示例
讓我們來看下面的實現以更好地理解:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countTriplets(vector<int>& arr) {
int ret = 0;
int n = arr.size();
for (int i = 1; i < n; i++) {
map<int, int> m;
int x1 = 0;
int x2 = 0;
for (int j = i - 1; j >= 0; j--) {
x1 = x1 ^ arr[j];
m[x1]++;
}
for (int j = i; j < n; j++) {
x2 = x2 ^ arr[j];
ret += m[x2];
}
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {2,3,1,6,7};
cout << (ob.countTriplets(v));
}輸入
{2,3,1,6,7}輸出
4
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP