Skip to content

Commit 5df38c3

Browse files
authored
Create 1649.Create-Sorted-Array-through-Instructions_v1.cpp
1 parent c180096 commit 5df38c3

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class Solution {
2+
int numSmaller[100005];
3+
int temp[100005];
4+
int count[100005];
5+
int nums[100005];
6+
int sorted[100005];
7+
int M = 1e9+7;
8+
public:
9+
int createSortedArray(vector<int>& instructions)
10+
{
11+
int n = instructions.size();
12+
for (int i=0; i<n; i++)
13+
{
14+
nums[i] = instructions[i];
15+
sorted[i] = instructions[i];
16+
}
17+
18+
helper(0, n-1);
19+
int ret = 0;
20+
for (int i=0; i<n; i++)
21+
{
22+
ret += min(numSmaller[i], i-count[nums[i]]-numSmaller[i]);
23+
ret %= M;
24+
count[nums[i]]++;
25+
}
26+
return ret;
27+
}
28+
29+
void helper(int a, int b)
30+
{
31+
if (a>=b) return;
32+
int mid = a+(b-a)/2;
33+
helper(a, mid);
34+
helper(mid+1, b);
35+
36+
for (int i=mid+1; i<=b; i++)
37+
{
38+
auto iter = lower_bound(sorted+a, sorted+mid+1, nums[i]);
39+
numSmaller[i] += iter-(sorted+a);
40+
}
41+
42+
int i=a, j=mid+1, p = 0;
43+
while (i<=mid && j<=b)
44+
{
45+
if (sorted[i]<=sorted[j])
46+
{
47+
temp[p] = sorted[i];
48+
i++;
49+
}
50+
else
51+
{
52+
temp[p] = sorted[j];
53+
j++;
54+
}
55+
p++;
56+
}
57+
while (i<=mid)
58+
{
59+
temp[p] = sorted[i];
60+
i++;
61+
p++;
62+
}
63+
while (j<=b)
64+
{
65+
temp[p] = sorted[j];
66+
j++;
67+
p++;
68+
}
69+
for (int i=0; i<b-a+1; i++)
70+
sorted[a+i] = temp[i];
71+
}
72+
};

0 commit comments

Comments
 (0)