-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskyline problem.java
More file actions
70 lines (62 loc) · 2.1 KB
/
Copy pathskyline problem.java
File metadata and controls
70 lines (62 loc) · 2.1 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
class Edge {
int x;
int height;
boolean isStart;
public Edge(int x, int height, boolean isStart)
{
this.x = x;
this.height = height;
this.isStart = isStart;
}
}
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> result = new ArrayList<int[]>();
if(buildings == null||buildings.length == 0 ||buildings[0].length == 0)
return result;
List<Edge> edges = new ArrayList<Edge>();
for(int[] building : buildings)
{
Edge startEdge = new Edge(building[0], building[2], true);
edges.add(startEdge);
Edge endEdge = new Edge(building[1], building[2], false);
edges.add(endEdge);
}
Collections.sort(edges, new Comparator<Edge>(){
public int compare(Edge a, Edge b){
if(a.x != b.x)
return Integer.compare(a.x, b.x);
if(a.isStart && b.isStart)
return Integer.compare(b.height, a.height);
if(!a.isStart && !b.isStart)
return Integer.compare(a.height, b.height);
return a.isStart ? -1:1;
}
});
PriorityQueue<Integer> map = new PriorityQueue<Integer>(10, Collections.reverseOrder());
for(Edge edge: edges)
{
if(edge.isStart)
{
if(map.isEmpty() || edge.height > map.peek()) {
result.add(new int[] {
edge.x, edge.height
});
}
map.add(edge.height);
}
else
{
map.remove(edge.height);
if(map.isEmpty()) {
result.add(new int[] {edge.x, 0});
}
else if(edge.height > map.peek())
{
result.add(new int[] {edge.x, map.peek()});
}
}
}
return result;
}
}