Approach
Sorting and greedy selection
For Rectangle Area II, 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
- 52 lines of Java from the credited upstream file 850.java.
- The implementation visibly relies on sequence storage.
- 3 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 rectangleArea(int[][] rectangles) {3 record Event(int x, int y1, int y2, char type) {}4 final int MOD = 1_000_000_007;5 List<Event> events = new ArrayList<>();6 7 for (int[] r : rectangles) {8 events.add(new Event(r[0], r[1], r[3], 's'));9 events.add(new Event(r[2], r[1], r[3], 'e'));10 }11 12 Collections.sort(events, Comparator.comparingInt(Event::x));13 14 long ans = 0;15 int prevX = 0;16 List<Pair<Integer, Integer>> yPairs = new ArrayList<>();17 18 for (Event e : events) {19 if (e.x > prevX) {20 final int width = e.x - prevX;21 ans = (ans + width * getHeight(yPairs)) % MOD;22 prevX = e.x;23 }24 if (e.type == 's') {25 yPairs.add(new Pair<>(e.y1, e.y2));26 Collections.sort(yPairs, Comparator.comparingInt(Pair::getKey));27 } else { 28 yPairs.remove(new Pair<>(e.y1, e.y2));29 }30 }31 32 return (int) (ans % MOD);33 }34 35 private long getHeight(List<Pair<Integer, Integer>> yPairs) {36 int height = 0;37 int prevY = 0;38 39 for (Pair<Integer, Integer> pair : yPairs) {40 final int y1 = pair.getKey();41 final int y2 = pair.getValue();42 prevY = Math.max(prevY, y1);43 if (y2 > prevY) {44 height += y2 - prevY;45 prevY = y2;46 }47 }48 49 return height;50 }51}52