-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathbest-reachable-tower.cpp
More file actions
43 lines (41 loc) · 1.27 KB
/
best-reachable-tower.cpp
File metadata and controls
43 lines (41 loc) · 1.27 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
// Time: O(n)
// Space: O(1)
// array
class Solution {
public:
vector<int> bestTower(vector<vector<int>>& towers, vector<int>& center, int radius) {
int best = -1, best_x = -1, best_y = -1;
for (const auto& t : towers) {
const auto& x = t[0], &y = t[1], &q = t[2];
if (!(abs(x - center[0]) + abs(y - center[1]) <= radius)) {
continue;
}
if (q > best) {
best = q;
best_x = x;
best_y = y;
} else if (q == best && (x < best_x || (x == best_x && y < best_y))) {
best_x = x;
best_y = y;
}
}
return best != -1 ? vector{best_x, best_y} : vector{-1, -1};
}
};
// Time: O(n)
// Space: O(1)
// array
class Solution2 {
public:
vector<int> bestTower(vector<vector<int>>& towers, vector<int>& center, int radius) {
vector<int> result(3, 1);
for (const auto& t : towers) {
const auto& x = t[0], &y = t[1], &q = t[2];
if (!(abs(x - center[0]) + abs(y - center[1]) <= radius)) {
continue;
}
result = min(result, {-q, x, y});
}
return result[0] != 1 ? vector{result[1], result[2]} : vector{-1, -1};
}
};