- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 57 lines of Java from the credited upstream file 218.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 List<List<Integer>> getSkyline(int[][] buildings) {3 final int n = buildings.length;4 if (n == 0)5 return new ArrayList<>();6 if (n == 1) {7 final int left = buildings[0][0];8 final int right = buildings[0][1];9 final int height = buildings[0][2];10 List<List<Integer>> ans = new ArrayList<>();11 ans.add(new ArrayList<>(List.of(left, height)));12 ans.add(new ArrayList<>(List.of(right, 0)));13 return ans;14 }15 16 List<List<Integer>> leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2));17 List<List<Integer>> rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n));18 return merge(leftSkyline, rightSkyline);19 }20 21 private List<List<Integer>> merge(List<List<Integer>> left, List<List<Integer>> right) {22 List<List<Integer>> ans = new ArrayList<>();23 int i = 0; 24 int j = 0; 25 int leftY = 0;26 int rightY = 0;27 28 while (i < left.size() && j < right.size())29 30 if (left.get(i).get(0) < right.get(j).get(0)) {31 leftY = left.get(i).get(1); 32 addPoint(ans, left.get(i).get(0), Math.max(left.get(i++).get(1), rightY));33 } else {34 rightY = right.get(j).get(1); 35 addPoint(ans, right.get(j).get(0), Math.max(right.get(j++).get(1), leftY));36 }37 38 while (i < left.size())39 addPoint(ans, left.get(i).get(0), left.get(i++).get(1));40 41 while (j < right.size())42 addPoint(ans, right.get(j).get(0), right.get(j++).get(1));43 44 return ans;45 }46 47 private void addPoint(List<List<Integer>> ans, int x, int y) {48 if (!ans.isEmpty() && ans.get(ans.size() - 1).get(0) == x) {49 ans.get(ans.size() - 1).set(1, y);50 return;51 }52 if (!ans.isEmpty() && ans.get(ans.size() - 1).get(1) == y)53 return;54 ans.add(new ArrayList<>(List.of(x, y)));55 }56}57