Skip to content

Commit 2e80be0

Browse files
committed
https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
1 parent 4295c15 commit 2e80be0

File tree

4 files changed

+1036
-5
lines changed

4 files changed

+1036
-5
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
14+
1315
https://leetcode.cn/problems/rank-from-stream-lcci/
1416

1517
https://leetcode.cn/problems/minimum-cost-to-hire-k-workers/

rank-from-stream-lcci/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
export default class StreamRank {
2-
#bit = new BinaryIndexTree(50002);
2+
#bit = new BinaryIndexTree(50001);
33
constructor() {}
44

55
track(x: number): void {
6-
this.#bit.change(x + 1, 1);
6+
this.#bit.update(x + 1, 1);
77
}
88

99
getRankOfNumber(x: number): number {
@@ -16,10 +16,10 @@ export class BinaryIndexTree {
1616
}
1717
#tree: number[];
1818
constructor(public size: number) {
19-
this.#tree = Array(size).fill(0);
19+
this.#tree = Array(size+1).fill(0);
2020
}
21-
change(i: number, x: number) {
22-
for (let p = i; p < this.size; p += BinaryIndexTree.lowbit(p)) {
21+
update(i: number, x: number) {
22+
for (let p = i; p <= this.size; p += BinaryIndexTree.lowbit(p)) {
2323
this.#tree[p] += x;
2424
}
2525
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { BinaryIndexTree } from "../rank-from-stream-lcci/index.ts";
2+
import { le as binarySearch } from "https://esm.sh/@masx200/[email protected]";
3+
export default function reversePairs(nums: number[]): number {
4+
const n = nums.length;
5+
const tmp = Array.from(nums);
6+
tmp.sort((a, b) => a - b);
7+
for (let i = 0; i < n; ++i) {
8+
nums[i] = binarySearch(tmp, nums[i]) + 1;
9+
}
10+
const bit = new BinaryIndexTree(n);
11+
let ans = 0;
12+
for (let i = n - 1; i >= 0; i--) {
13+
ans += bit.query(nums[i] - 1);
14+
bit.update(nums[i], 1);
15+
}
16+
return ans;
17+
}

0 commit comments

Comments
 (0)