1
+ // Runtime: 390 ms (Top 96.30%) | Memory: 112.1 MB (Top 64.81%)
1
2
class Solution {
2
3
public:
3
4
vector<bitset<101 >> tree;
4
5
vector<int > minDifference (vector<int >& nums, vector<vector<int >>& queries) {
5
6
int n = nums.size ();
6
-
7
+
7
8
tree = vector<bitset<101 >>(4 *(n+1 ) + 1 );
8
9
buildtree (1 , 0 , n-1 , nums);
9
-
10
+
10
11
vector<int > ans;
11
12
for (auto &e: queries){
12
13
auto finalOnesRepresentations = query (1 , 0 , n-1 , e[0 ], e[1 ]);
13
-
14
+
14
15
// find the first 1
15
16
int i = 0 ;
16
17
while (i < 101 and finalOnesRepresentations[i] != 1 ){
17
18
i++;
18
19
}
19
-
20
+
20
21
int gap = INT_MAX;
21
22
int prev = i;
22
23
i++;
@@ -27,37 +28,37 @@ class Solution {
27
28
prev = i;
28
29
}
29
30
}
30
- ans.push_back (gap == INT_MAX ? -1 : gap);
31
+ ans.push_back (gap == INT_MAX ? -1 : gap);
31
32
}
32
33
return ans;
33
34
}
34
-
35
+
35
36
bitset<101 > query (int index, int s, int e, int qs, int qe){
36
-
37
+
37
38
if (s > e) return bitset<101 >();
38
39
if (e < qs || s > qe) return bitset<101 >();
39
40
if (qs <= s and e <= qe) return tree[index ];
40
-
41
+
41
42
int mid = (s+e)/2 ;
42
43
auto left = query (index *2 , s, mid, qs, qe);
43
44
auto right = query (index *2 +1 , mid+1 , e, qs , qe);
44
45
return left | right;
45
46
}
46
-
47
+
47
48
void buildtree (int index, int s, int e, vector<int >& a){
48
-
49
+
49
50
if (s > e)return ;
50
-
51
+
51
52
if (s==e){
52
53
bitset<101 > b;
53
54
b[a[s]] = 1 ;
54
55
tree[index ] = b;
55
56
return ;
56
57
}
57
-
58
+
58
59
int mid = (s+e)/2 ;
59
60
buildtree (index *2 , s, mid, a);
60
61
buildtree (index *2 +1 , mid+1 , e, a);
61
62
tree[index ] = tree[index *2 ] | tree[index *2 +1 ];
62
63
}
63
- };
64
+ };
0 commit comments