classSolution: defnumberOfPairs(self, a: List[int], nums2: List[int], diff: int) -> int: for i, x inenumerate(nums2): a[i] -= x b = sorted(set(a)) # 配合下面的二分,离散化
ans = 0 t = BIT(len(b) + 1) for x in a: ans += t.query(bisect_right(b, x + diff)) t.add(bisect_left(b, x) + 1) return ans
classBIT: def__init__(self, n): self.tree = [0] * n
defadd(self, x): while x < len(self.tree): self.tree[x] += 1 x += x & -x
defquery(self, x): res = 0 while x > 0: res += self.tree[x] x &= x - 1 return res
classSolution { publiclongnumberOfPairs(int[] a, int[] nums2, int diff) { varn= a.length; for (vari=0; i < n; ++i) a[i] -= nums2[i]; varb= Arrays.stream(a).distinct().sorted().toArray(); // 配合下面的二分,离散化
varans=0L; vart=newBIT(b.length + 1); for (var x : a) { ans += t.query(lowerBound(b, x + diff + 1)); t.add(lowerBound(b, x) + 1); } return ans; }
privateintlowerBound(int[] a, int x) { intleft=0, right = a.length; while (left < right) { varmid= left + (right - left) / 2; if (a[mid] < x) left = mid + 1; else right = mid; } return left; } }
classBIT { privatefinalint[] tree;
publicBIT(int n) { tree = newint[n]; }
publicvoidadd(int x) { while (x < tree.length) { ++tree[x]; x += x & -x; } }
publicintquery(int x) { varres=0; while (x > 0) { res += tree[x]; x &= x - 1; } return res; } }
voidadd(int x){ while (x < tree.size()) { ++tree[x]; x += x & -x; } }
intquery(int x){ int res = 0; while (x > 0) { res += tree[x]; x &= x - 1; } return res; } };
classSolution { public: longlongnumberOfPairs(vector<int> &a, vector<int> &nums2, int diff){ int n = a.size(); for (int i = 0; i < n; ++i) a[i] -= nums2[i]; auto b = a; sort(b.begin(), b.end()); b.erase(unique(b.begin(), b.end()), b.end()); // 配合下面的二分,离散化
long ans = 0L; auto t = newBIT(n + 1); for (int x : a) { ans += t->query(upper_bound(b.begin(), b.end(), x + diff) - b.begin()); t->add(lower_bound(b.begin(), b.end(), x) - b.begin() + 1); } return ans; } };
funcnumberOfPairs(a, nums2 []int, diff int) (ans int64) { for i, x := range nums2 { a[i] -= x } // 配合下面的二分,离散化 set := map[int]struct{}{} for _, v := range a { set[v] = struct{}{} } b := make(sort.IntSlice, 0, len(set)) for x := range set { b = append(b, x) } sort.Ints(b)
t := make(BIT, len(a)+1) for _, x := range a { ans += int64(t.query(b.Search(x + diff + 1))) t.add(b.Search(x) + 1) } return }
type BIT []int
func(t BIT) add(x int) { for x < len(t) { t[x]++ x += x & -x } }
func(t BIT) query(x int) (res int) { for x > 0 { res += t[x] x &= x - 1 } return }