-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path218_the_skyline_problem.java
More file actions
51 lines (44 loc) · 1.49 KB
/
218_the_skyline_problem.java
File metadata and controls
51 lines (44 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Pair {
int key;
int val;
public Pair(int key, int val) {
this.key = key;
this.val = val;
}
}
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
List<List<Integer>> skyline = new ArrayList<>();
if (buildings == null || buildings.length == 0 || buildings[0].length == 0) {
return skyline;
}
PriorityQueue<Pair> pq = new PriorityQueue<>(new Comparator<Pair>() {
public int compare(Pair p1, Pair p2) {
if (p1.key == p2.key) {
return p1.val - p2.val;
}
return p1.key - p2.key;
}
});
for (int i = 0; i < buildings.length; i++) {
pq.offer(new Pair(buildings[i][0], -buildings[i][2]));
pq.offer(new Pair(buildings[i][1], buildings[i][2]));
}
PriorityQueue<Integer> skylinePQ = new PriorityQueue<>((a, b) -> b - a);
skylinePQ.offer(0);
int pre = -1;
while (!pq.isEmpty()) {
Pair p = pq.poll();
if (p.val < 0) {
skylinePQ.offer(-p.val);
} else {
skylinePQ.remove(p.val);
}
if (pre != skylinePQ.peek()) {
pre = skylinePQ.peek();
skyline.add(new ArrayList(Arrays.asList(p.key, skylinePQ.peek())));
}
}
return skyline;
}
}