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
- 39 lines of Java from the credited upstream file 2015.java.
- 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 int[][] averageHeightOfBuildings(int[][] buildings) {3 List<int[]> ans = new ArrayList<>();4 List<Pair<Integer, Integer>> events = new ArrayList<>();5 6 for (int[] b : buildings) {7 final int start = b[0];8 final int end = b[1];9 final int height = b[2];10 events.add(new Pair<>(start, height));11 events.add(new Pair<>(end, -height));12 }13 14 Collections.sort(events, Comparator.comparingInt(Pair::getKey));15 16 int prev = 0;17 int count = 0;18 int sumHeight = 0;19 20 for (Pair<Integer, Integer> event : events) {21 final int curr = event.getKey();22 final int height = event.getValue();23 if (sumHeight > 0 && curr > prev) {24 final int avgHeight = sumHeight / count;25 if (!ans.isEmpty() && ans.get(ans.size() - 1)[1] == prev &&26 avgHeight == ans.get(ans.size() - 1)[2])27 ans.get(ans.size() - 1)[1] = curr;28 else29 ans.add(new int[] {prev, curr, avgHeight});30 }31 sumHeight += height;32 count += height > 0 ? 1 : -1;33 prev = curr;34 }35 36 return ans.stream().toArray(int[][] ::new);37 }38}39