Skip to content

Commit 3e1e76d

Browse files
authored
Create average-height-of-buildings-in-each-segment.cpp
1 parent d4bd69c commit 3e1e76d

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int>> averageHeightOfBuildings(vector<vector<int>>& buildings) {
7+
vector<tuple<int, int, int>> points;
8+
for (const auto& b : buildings) {
9+
points.emplace_back(b[0], 1, b[2]);
10+
points.emplace_back(b[1], -1, b[2]);
11+
}
12+
sort(begin(points), end(points));
13+
vector<vector<int>> result;
14+
int total = 0, cnt = 0;
15+
int prev = -1;
16+
for (const auto& [curr, c, h] : points) {
17+
if (cnt && prev != curr) {
18+
if (!empty(result) && result.back()[1] == prev && result.back()[2] == total / cnt) {
19+
result.back()[1] = curr;
20+
} else {
21+
result.push_back({prev, curr, total / cnt});
22+
}
23+
}
24+
total += h * c;
25+
cnt += c;
26+
prev = curr;
27+
}
28+
return result;
29+
}
30+
};
31+
32+
// Time: O(nlogn)
33+
// Space: O(n)
34+
class Solution2 {
35+
public:
36+
vector<vector<int>> averageHeightOfBuildings(vector<vector<int>>& buildings) {
37+
unordered_map<int, pair<int, int>> count;
38+
for (const auto& b : buildings) {
39+
count[b[0]] = {count[b[0]].first + 1, count[b[0]].second + b[2]};
40+
count[b[1]] = {count[b[1]].first - 1, count[b[1]].second - b[2]};
41+
}
42+
vector<tuple<int, int, int>> points;
43+
for (const auto& [k, v] : count) {
44+
points.emplace_back(k, v.first, v.second);
45+
}
46+
sort(begin(points), end(points));
47+
vector<vector<int>> result;
48+
int total = 0, cnt = 0;
49+
int prev = -1;
50+
for (const auto& [curr, c, h] : points) {
51+
if (cnt) {
52+
if (!empty(result) && result.back()[1] == prev && result.back()[2] == total / cnt) {
53+
result.back()[1] = curr;
54+
} else {
55+
result.push_back({prev, curr, total / cnt});
56+
}
57+
}
58+
total += h;
59+
cnt += c;
60+
prev = curr;
61+
}
62+
return result;
63+
}
64+
};

0 commit comments

Comments
 (0)