Skip to content

Commit d63d2ff

Browse files
committed
https://leetcode.cn/problems/rank-from-stream-lcci/
1 parent 0079b99 commit d63d2ff

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
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/rank-from-stream-lcci/
14+
1315
https://leetcode.cn/problems/minimum-cost-to-hire-k-workers/
1416

1517
https://leetcode.cn/problems/number-of-closed-islands/

range-sum-query-2d-mutable/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,6 @@ export default class NumMatrix {
4141
return sum;
4242
}
4343
}
44-
function lowbit(a: number) {
44+
export function lowbit(a: number) {
4545
return a & -a;
4646
}

rank-from-stream-lcci/index.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
export default class StreamRank {
2+
#bit = new BinaryIndexTree(50002);
3+
constructor() {}
4+
5+
track(x: number): void {
6+
this.#bit.change(x + 1, 1);
7+
}
8+
9+
getRankOfNumber(x: number): number {
10+
return this.#bit.query(x + 1);
11+
}
12+
}
13+
export class BinaryIndexTree {
14+
static lowbit(x: number) {
15+
return x & -x;
16+
}
17+
#tree: number[];
18+
constructor(public size: number) {
19+
this.#tree = Array(size).fill(0);
20+
}
21+
change(i: number, x: number) {
22+
for (let p = i; p < this.size; p += BinaryIndexTree.lowbit(p)) {
23+
this.#tree[p] += x;
24+
}
25+
}
26+
query(n: number) {
27+
let ans = 0;
28+
for (let p = n; p > 0; p -= BinaryIndexTree.lowbit(p)) {
29+
ans += this.#tree[p];
30+
}
31+
return ans;
32+
}
33+
}

0 commit comments

Comments
 (0)