forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
finding-the-number-of-visible-mountains.cpp
53 lines (49 loc) · 1.68 KB
/
finding-the-number-of-visible-mountains.cpp
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
// Time: O(nlogn)
// Space: O(1)
// math, sort
class Solution {
public:
int visibleMountains(vector<vector<int>>& peaks) {
sort(begin(peaks), end(peaks), [](const auto& a, const auto& b) {
const int x1 = a[0], y1 = a[1];
const int x2 = b[0], y2 = b[1];
return x1 - y1 != x2 - y2 ? x1 - y1 < x2 - y2 : x1 + y1 > x2 + y2; // rotate points by 45 degrees and we only care the largest new y in the same new x
});
int result = 0;
for (int i = 0, mx = 0; i < size(peaks); ++i) {
if (peaks[i][0] + peaks[i][1] <= mx) {
continue;
}
mx = peaks[i][0] + peaks[i][1];
if (i + 1 == size(peaks) || peaks[i + 1] != peaks[i]) {
++result;
}
}
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
// sort, mono stack
class Solution2 {
public:
int visibleMountains(vector<vector<int>>& peaks) {
const auto& is_covered = [](const auto& a, const auto& b) {
const int x1 = a[0], y1 = a[1];
const int x2 = b[0], y2 = b[1];
return x2 - y2 <= x1 - y1 && x1 + y1 <= x2 + y2;
};
sort(begin(peaks), end(peaks));
vector<int> stk;
for (int i = 0; i < size(peaks); ++i) {
while (!empty(stk) && is_covered(peaks[stk.back()], peaks[i])) {
stk.pop_back();
}
if ((i - 1 == -1 || peaks[i - 1] != peaks[i]) &&
(empty(stk) || !is_covered(peaks[i], peaks[stk.back()]))) { // not duplicted and not covered
stk.emplace_back(i);
}
}
return size(stk);
}
};