1
var goodTriplets = function (nums1, nums2) {4
for (let i = 0; i < n; i++) nums2_idx[nums2[i]] = i;6
for (let i = 0; i < n; i++) idxs[i] = nums2_idx[nums1[i]];8
let smallerLeft = getSmallerLeft(idxs); // smallerLeft[i] = number of indices to the left of i smaller than idxs[i] in both nums1 and nums29
let biggerRight = getBiggerRight(idxs); // biggerRight[i] = number of indices to the right of i bigger than idxs[i] in both nums1 and nums211
for (let i = 1; i < n - 1; i++) {12
ans += smallerLeft[i] * biggerRight[i];17
function getSmallerLeft(idxs) {19
res = Array(n).fill(0);20
let segTree = new SegmentTree(n);21
for (let i = 0; i < n; i++) {22
res[i] = segTree.getSum(0, idxs[i] - 1);23
segTree.update(idxs[i], 1);28
function getBiggerRight(idxs) {30
res = Array(n).fill(0);31
let segTree = new SegmentTree(n);32
for (let i = n - 1; i >= 0; i--) {33
res[i] = segTree.getSum(idxs[i] + 1, n - 1);34
segTree.update(idxs[i], 1);42
this.segTree = Array(n * 2).fill(0);47
this.segTree[idx] += val;48
idx = Math.floor(idx / 2);51
this.segTree[idx] = this.segTree[idx * 2] + this.segTree[idx * 2 + 1];52
idx = Math.floor(idx / 2);58
let left_idx = left + n,59
right_idx = right + n;60
// left must be even, right must be odd61
while (left_idx <= right_idx) {62
if (left_idx % 2 === 1) sum += this.segTree[left_idx++];63
if (right_idx % 2 === 0) sum += this.segTree[right_idx--];64
left_idx = Math.floor(left_idx / 2);65
right_idx = Math.floor(right_idx / 2);