Skip to content

Commit 9cd2c5a

Browse files
authored
Create 2179. Count Good Triplets in an Array (#768)
2 parents 2352e11 + 4d38264 commit 9cd2c5a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

2179. Count Good Triplets in an Array

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution
2+
{
3+
public:
4+
using ll = long long;
5+
vector<ll> bit1, bit2;
6+
int n;
7+
void update(vector<ll>& bit, int i, ll val)
8+
{
9+
for (++i; i <= n; i += (i & -i))
10+
bit[i] += val;
11+
}
12+
ll query(const vector<ll>& bit, int i)
13+
{
14+
ll res = 0;
15+
for (++i; i > 0; i -= (i & -i))
16+
res += bit[i];
17+
return res;
18+
}
19+
long long goodTriplets(vector<int>& nums1, vector<int>& nums2)
20+
{
21+
n = nums1.size();
22+
vector<int> pos(n);
23+
for (int i = 0; i < n; ++i)
24+
pos[nums2[i]] = i;
25+
for (int i = 0; i < n; ++i)
26+
nums1[i] = pos[nums1[i]];
27+
bit1.assign(n + 2, 0);
28+
bit2.assign(n + 2, 0);
29+
ll ans = 0;
30+
for (int i = n - 1; i >= 0; --i)
31+
{
32+
int x = nums1[i];
33+
ll val = query(bit1, n - 1) - query(bit1, x);
34+
ll trip = query(bit2, n - 1) - query(bit2, x);
35+
ans += trip;
36+
update(bit2, x, val);
37+
update(bit1, x, 1);
38+
}
39+
return ans;
40+
}
41+
};

0 commit comments

Comments
 (0)