Skip to content

Commit ae97a54

Browse files
committed
Update 218_The_Skyline_Problem.java
1 parent f5b3789 commit ae97a54

File tree

1 file changed

+16
-27
lines changed

1 file changed

+16
-27
lines changed

Arrays/218_The_Skyline_Problem.java

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,32 @@
11
class Solution {
22
public List<List<Integer>> getSkyline(int[][] buildings) {
33
List<List<Integer>> result = new ArrayList<>();
4-
List<int[]> heights = new ArrayList<>();
54

6-
for (int[] building : buildings) {
7-
heights.add(new int[] { building[0], -building[2] });
8-
heights.add(new int[] { building[1], building[2] });
9-
}
5+
List<int[]> points = new ArrayList<>();
106

11-
Collections.sort(heights, (a, b) -> {
12-
if (a[0] == b[0])
13-
return a[1] - b[1];
14-
return a[0] - b[0];
15-
});
7+
for (int[] b : buildings) {
8+
points.add(new int[] { b[0], -b[2] });
9+
points.add(new int[] { b[1], b[2] });
10+
}
1611

17-
TreeMap<Integer, Integer> pq = new TreeMap<>();
18-
int prevMaxHeight = 0;
12+
Collections.sort(points, (p1, p2) -> p1[0] == p2[0] ? p1[1] - p2[1] : p1[0] - p2[0]);
1913

20-
pq.put(prevMaxHeight, 1);
14+
int maxHeight = 0;
15+
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
16+
pq.offer(maxHeight);
2117

22-
for (int[] h : heights) {
23-
int xCoord = h[0];
24-
int height = h[1];
18+
for (int[] p : points) {
19+
int xCoord = p[0], height = p[1];
2520

2621
if (height < 0) {
27-
pq.put(-height, pq.getOrDefault(-height, 0) + 1);
22+
pq.offer(Math.abs(height));
2823
} else {
29-
if (pq.get(height) > 1) {
30-
pq.put(height, pq.get(height) - 1);
31-
} else {
32-
pq.remove(height);
33-
}
24+
pq.remove(height);
3425
}
3526

36-
int maxHeightAtXCoord = pq.lastKey();
37-
38-
if (maxHeightAtXCoord != prevMaxHeight) {
39-
result.add(Arrays.asList(new Integer[] { xCoord, maxHeightAtXCoord }));
40-
prevMaxHeight = maxHeightAtXCoord;
27+
if (maxHeight != pq.peek()) {
28+
maxHeight = pq.peek();
29+
result.add(Arrays.asList(xCoord, maxHeight));
4130
}
4231
}
4332

0 commit comments

Comments
 (0)