-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-sorted-array-through-instructions.java
71 lines (58 loc) · 1.57 KB
/
create-sorted-array-through-instructions.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class Solution {
public int createSortedArray(int[] A) {
int res = 0;
int n = A.length;
int mod = (int) 1e9 + 7;
int[] c = new int[(int) (10e5) + 1]; // counts of all possible number 1_000_000
for (int i = 0; i < n; i++) {
// first call to get with get count of all numbers less than A[i], second call
// get all numbers up to A[i] including A[i] and subtract it with the position
// in the array. This will give up the count of number in the array that are
// greater than A[i]
int min = (res + Math.min(get(A[i] - 1, c), i - get(A[i], c))) % mod;
res = min;
update(A[i], c); // will increment the occurrence of A[i] in our tree
}
return res;
}
public void update(int x, int[] c) {
while (x < 100001) {
c[x]++;
x += x & -x;
}
}
public int get(int x, int[] c) {
int res = 0;
while (x > 0) {
res += c[x];
x -= x & -x;
}
return res;
}
}
// O(n^2)
class Solution {
public int createSortedArray(int[] A) {
int res = 0;
int n = A.length;
int mod = (int) 1e9 + 7;
int[] c = new int[(int) (10e5) + 1]; // counts of all possible number 1_000_000
for (int i = 0; i < n; i++) {
int min = (res + Math.min(get(A[i] - 1, c), i - get(A[i], c))) % mod;
res = min;
update(A[i], c); // will increment the occurance of A[i] in our tree
}
return res;
}
public void update(int x, int[] c) {
c[x]++;
}
public int get(int x, int[] c) {
int res = 0;
while (x > 0) {
res += c[x];
x--;
}
return res;
}
}