
Sponsored
Sponsored
The Sweep Line algorithm involves moving a vertical line from left to right over the x-coordinates and maintaining a list of currently active buildings using a max-heap. The priority queue helps keep track of the tallest building at each point. As the line reaches the start of a new building, add it to the heap, and as it reaches the end of a building, remove it. The key points are detected based on changes in the maximum height at points where buildings start or end.
Time Complexity: O(N log N), where N is the number of events (two for each building).
Space Complexity: O(N), as we store up to N building heights in the heap.
1import java.util.*;
2
3public class Skyline {
4 public List<List<Integer>> getSkyline(int[][] buildings) {
5 List<int[]> events = new ArrayList<>();
6 for (int[] b : buildings) {
7 events.add(new int[]{b[0], -b[2]});
8 events.add(new int[]{b[1], b[2]});
9 }
10 events.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
11
12 List<List<Integer>> res = new ArrayList<>();
13 PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
14 pq.add(0);
15 int prev = 0;
16 for (int[] e : events) {
17 if (e[1] < 0) {
18 pq.add(-e[1]);
19 } else {
20 pq.remove(e[1]);
21 }
22 int current = pq.peek();
23 if (prev != current) {
24 res.add(Arrays.asList(e[0], current));
25 prev = current;
26 }
27 }
28 return res;
29 }
30}This Java implementation is similar to the Python approach. It collects all start and end events, processes them using a priority queue to keep track of the tallest buildings, and adds only the necessary key points to the result when there is a change in the skyline height.
This approach involves breaking down the problem using the divide and conquer strategy. The buildings array is split into two halves recursively. The base case is a single building, where the skyline can directly be calculated. The results are then merged, taking care of overlapping heights and ensuring continuity and distinct key points.
Time Complexity: O(N log N), due to division of buildings and merging.
Space Complexity: O(N), needing space for recursive stack and individual skyline lists.
1function
The JavaScript solution applies a divide and conquer algorithm to split the problem space into manageable segments, solving for each individually, and consolidating results with aligned key height changes.