File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(nlogn)
2
+ // Space: O(n)
3
+
4
+ // bit, fenwick tree, combinatorics
5
+ class Solution {
6
+ public:
7
+ long long goodTriplets (vector<int >& nums1, vector<int >& nums2) {
8
+ unordered_map<int , int > lookup;
9
+ for (int i = 0 ; i < size (nums1); ++i) {
10
+ lookup[nums1[i]] = i;
11
+ }
12
+ int64_t result = 0 ;
13
+ BIT bit (size (nums1));
14
+ for (int i = 0 ; i < size (nums2); ++i) {
15
+ const int64_t smaller = bit.query (lookup[nums2[i]] - 1 );
16
+ const int64_t larger = (size (nums1) - (lookup[nums2[i]] + 1 )) - (i - smaller);
17
+ result += smaller * larger;
18
+ bit.add (lookup[nums2[i]], 1 );
19
+ }
20
+ return result;
21
+ }
22
+
23
+ private:
24
+ class BIT {
25
+ public:
26
+ BIT (int n) : bit_(n + 1 ) { // 0-indexed
27
+ }
28
+
29
+ void add (int i, int val) {
30
+ ++i;
31
+ for (; i < size (bit_); i += lower_bit (i)) {
32
+ bit_[i] += val;
33
+ }
34
+ }
35
+
36
+ int query (int i) const {
37
+ ++i;
38
+ int total = 0 ;
39
+ for (; i > 0 ; i -= lower_bit (i)) {
40
+ total += bit_[i];
41
+ }
42
+ return total;
43
+ }
44
+
45
+ private:
46
+ int lower_bit (int i) const {
47
+ return i & -i;
48
+ }
49
+
50
+ vector<int > bit_;
51
+ };
52
+ };
You can’t perform that action at this time.
0 commit comments