-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2940-building-alice-bob.dart
97 lines (86 loc) · 2.35 KB
/
2940-building-alice-bob.dart
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
94
95
96
97
class Solution {
List<int> leftmostBuildingQueries(
List<int> heights, List<List<int>> queries) {
List<IndexedQuery> indexedQueries = getIndexedQueries(queries);
List<int> ans = List.filled(queries.length, -1);
List<int> stack = [];
int heightsIndex = heights.length - 1;
for (var indexedQuery in indexedQueries) {
int queryIndex = indexedQuery.queryIndex;
int a = indexedQuery.a;
int b = indexedQuery.b;
if (a == b || heights[a] < heights[b]) {
// same building
ans[queryIndex] = b;
} else {
// directly jump to Bob
// stack
while (heightsIndex > b) {
while (stack.isNotEmpty &&
heights[stack.last] <= heights[heightsIndex]) {
stack.removeLast();
}
stack.add(heightsIndex--);
}
// binary search
int meetingIndex = lastGreater(stack, a, heights);
if (meetingIndex != -1) {
ans[queryIndex] = stack[meetingIndex];
}
}
}
return ans;
}
List<IndexedQuery> getIndexedQueries(List<List<int>> queries) {
List<IndexedQuery> indexedQueries = [];
for (int i = 0; i < queries.length; i++) {
int a = queries[i][0];
int b = queries[i][1];
indexedQueries.add(IndexedQuery(i, a < b ? a : b, a < b ? b : a));
}
indexedQueries.sort((x, y) => y.b.compareTo(x.b)); // Sort descending by `b`
return indexedQueries;
}
int lastGreater(List<int> stack, int target, List<int> heights) {
int l = -1;
int r = stack.length - 1;
while (l < r) {
int m = (l + r + 1) ~/ 2;
if (heights[stack[m]] > heights[target]) {
l = m;
} else {
r = m - 1;
}
}
return l;
}
}
class IndexedQuery {
final int queryIndex;
final int a;
final int b;
IndexedQuery(this.queryIndex, this.a, this.b);
}
void main() {
Solution solution = Solution();
List<int> heights = [5, 3, 8, 2, 6, 1, 4, 6];
List<List<int>> queries = [
[0, 7],
[3, 5],
[5, 2],
[3, 0],
[1, 6]
];
print(solution.leftmostBuildingQueries(
heights, queries)); // Output: [7, 6, -1, 4, 6]
List<int> heights2 = [6, 4, 8, 5, 2, 7];
List<List<int>> queries2 = [
[0, 1],
[0, 3],
[2, 4],
[3, 4],
[2, 2]
];
//Output: [2,5,-1,5,2]
print(solution.leftmostBuildingQueries(heights2, queries2));
}