forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
39 lines (35 loc) · 925 Bytes
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = new Array(n + 1).fill(0);
}
public update(x: number, v: number): void {
while (x <= this.n) {
this.c[x] += v;
x += x & -x;
}
}
public query(x: number): number {
let s = 0;
while (x > 0) {
s += this.c[x];
x -= x & -x;
}
return s;
}
}
function createSortedArray(instructions: number[]): number {
const m = Math.max(...instructions);
const tree = new BinaryIndexedTree(m);
let ans = 0;
const mod = 10 ** 9 + 7;
for (let i = 0; i < instructions.length; ++i) {
const x = instructions[i];
const cost = Math.min(tree.query(x - 1), i - tree.query(x));
ans = (ans + cost) % mod;
tree.update(x, 1);
}
return ans;
}