Approach
Sorting and greedy selection
For Average Height of Buildings in Each Segment, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 37 lines of C++ from the credited upstream file 2015.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> averageHeightOfBuildings(vector<vector<int>>& buildings) {4 vector<vector<int>> ans;5 vector<pair<int, int>> events;6 7 for (const vector<int>& b : buildings) {8 const int start = b[0];9 const int end = b[1];10 const int height = b[2];11 events.emplace_back(start, height);12 events.emplace_back(end, -height);13 }14 15 ranges::sort(events);16 17 int prev = 0;18 int count = 0;19 int sumHeight = 0;20 21 for (const auto& [curr, height] : events) {22 if (sumHeight > 0 && curr > prev) {23 const int avgHeight = sumHeight / count;24 if (!ans.empty() && ans.back()[1] == prev && avgHeight == ans.back()[2])25 ans.back()[1] = curr;26 else27 ans.push_back({prev, curr, avgHeight});28 }29 sumHeight += height;30 count += height > 0 ? 1 : -1;31 prev = curr;32 }33 34 return ans;35 }36};37