|
1 | 1 | class Solution {
|
2 | 2 | public List<List<Integer>> getSkyline(int[][] buildings) {
|
3 | 3 | List<List<Integer>> result = new ArrayList<>();
|
4 |
| - List<int[]> heights = new ArrayList<>(); |
5 | 4 |
|
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<>(); |
10 | 6 |
|
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 | + } |
16 | 11 |
|
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]); |
19 | 13 |
|
20 |
| - pq.put(prevMaxHeight, 1); |
| 14 | + int maxHeight = 0; |
| 15 | + PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); |
| 16 | + pq.offer(maxHeight); |
21 | 17 |
|
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]; |
25 | 20 |
|
26 | 21 | if (height < 0) {
|
27 |
| - pq.put(-height, pq.getOrDefault(-height, 0) + 1); |
| 22 | + pq.offer(Math.abs(height)); |
28 | 23 | } 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); |
34 | 25 | }
|
35 | 26 |
|
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)); |
41 | 30 | }
|
42 | 31 | }
|
43 | 32 |
|
|
0 commit comments