File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(nlogn)
2
+ // Space: O(n)
3
+
4
+ class BIT { // Fenwick Tree, 1-indexed
5
+ public:
6
+ BIT (int n) : bit_(n) {
7
+
8
+ }
9
+
10
+ void add (int i, int val) {
11
+ for (; i < bit_.size (); i += lower_bit (i)) {
12
+ bit_[i] += val;
13
+ }
14
+ }
15
+
16
+ int sum (int i) {
17
+ int sum = 0 ;
18
+ for (; i > 0 ; i -= lower_bit (i)) {
19
+ sum += bit_[i];
20
+ }
21
+ return sum;
22
+ }
23
+
24
+ inline int lower_bit (int i) {
25
+ return i & -i;
26
+ }
27
+
28
+ private:
29
+ vector<int > bit_;
30
+ };
31
+
32
+ class Solution {
33
+ public:
34
+ vector<int > processQueries (vector<int >& queries, int m) {
35
+ BIT bit (2 * m + 1 );
36
+ unordered_map<int , int > lookup;
37
+ for (int i = 1 ; i <= m; ++i) {
38
+ lookup[i] = m + i;
39
+ bit.add (m + i, 1 );
40
+ }
41
+ vector<int > result;
42
+ int curr = m;
43
+ for (const auto & q : queries) {
44
+ auto i = lookup[q]; lookup.erase (q);
45
+ result.emplace_back (bit.sum (i - 1 ));
46
+ bit.add (i, -1 );
47
+ lookup[q] = curr;
48
+ bit.add (curr--, 1 );
49
+ }
50
+ return result;
51
+ }
52
+ };
You can’t perform that action at this time.
0 commit comments