-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
44 lines (40 loc) · 1011 Bytes
/
Solution.java
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
40
41
42
43
44
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
this.c = new int[n + 1];
}
public void update(int x, int v) {
while (x <= n) {
c[x] += v;
x += x & -x;
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= x & -x;
}
return s;
}
}
class Solution {
public int createSortedArray(int[] instructions) {
int m = 0;
for (int x : instructions) {
m = Math.max(m, x);
}
BinaryIndexedTree tree = new BinaryIndexedTree(m);
int ans = 0;
final int mod = (int) 1e9 + 7;
for (int i = 0; i < instructions.length; ++i) {
int x = instructions[i];
int cost = Math.min(tree.query(x - 1), i - tree.query(x));
ans = (ans + cost) % mod;
tree.update(x, 1);
}
return ans;
}
}