forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreate Sorted Array through Instructions.cpp
93 lines (80 loc) · 2.19 KB
/
Create Sorted Array through Instructions.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Runtime: 1154 ms (Top 36.85%) | Memory: 229 MB (Top 24.81%)
class Solution {
public:
vector<int>seg;
int query(int index,int low,int high,int l,int r)
{
if(low>=l && high<=r)
{
return seg[index];
}
if(high<l || low>r)
return 0;
int mid=(low+high)/2;
int left=query(2*index+1,low,mid,l,r);
int right=query(2*index+2,mid+1,high,l,r);
return right+left;
}
void update(int index,int low,int high,int pos)
{
if(low==high)
{
seg[index]++;
return ;
}
else
{
int mid=(low+high)/2;
if(pos<=mid)
{
update(2*index+1,low,mid,pos);
}
else
{
update(2*index+2,mid+1,high,pos);
}
seg[index]=seg[2*index+1]+seg[2*index+2];
}
}
int createSortedArray(vector<int>& instructions) {
// using 100001 as 1e5 is the max element value
seg.resize(4*100001,0);
int mod=1e9+7;
int ans=0;
for(int i=0;i<instructions.size();i++)
{
int mi=query(0,0,100001,0,instructions[i]-1); //number of elements smaller than instruction[i]
int mx=query(0,0,100001,instructions[i]+1,100001); // number of elements greater than instruction[i]
update(0,0,100001,instructions[i]);
ans=(ans+min(mi,mx))%mod;
}
return ans;
/*TLE approch using STL
// 50/65 cases passed
int m=instructions.size();
vector<int>a;
int mod=1e9+7;
int ans=0;
int mxe=INT_MIN;
unordered_map<int,int>um;
for(auto x:instructions)
{
int xx=lower_bound(a.begin(),a.end(),x)-a.begin();
int n=a.size();
um[x]++;
mxe=max(mxe,x);
if(n==0)
{
a.push_back(x);
}
else
{
a.insert(a.begin()+xx,x);
int mi=xx;
int m=a.size();
ans=(ans+min(mi,m-mi-um[x]))%mod;
}
}
return ans;*/
}
};