-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateSortedArraythroughInstructions.cpp
More file actions
48 lines (42 loc) · 1.06 KB
/
createSortedArraythroughInstructions.cpp
File metadata and controls
48 lines (42 loc) · 1.06 KB
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
// Source: https://leetcode.com/problems/create-sorted-array-through-instructions/
// Author: Miao Zhang
// Date: 2021-05-25
class FenwickTree {
public:
FenwickTree(int n): sums_(n + 1) {}
void update(int i, int delta) {
while (i < sums_.size()) {
sums_[i] += delta;
i += lowbit(i);
}
}
int query(int i) const {
int sums = 0;
while (i > 0) {
sums += sums_[i];
i -= lowbit(i);
}
return sums;
}
private:
static inline int lowbit(int x) {
return x & (-x);
}
vector<int> sums_;
};
class Solution {
public:
int createSortedArray(vector<int>& instructions) {
int kMod = 1e9 + 7;
int n = instructions.size();
FenwickTree tree(1e5);
long res = 0;
for (int i = 0; i < n; i++) {
int lt = tree.query(instructions[i] - 1);
int gt = i - tree.query(instructions[i]);
res += min(lt, gt);
tree.update(instructions[i], 1);
}
return res % kMod;
}
};