Skip to content

Commit 88ca147

Browse files
committed
java priority queue
1 parent 5bdea91 commit 88ca147

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package BuildingOutline;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Created by Daniel on 17/06/15.
7+
*/
8+
public class Solution {
9+
class Building implements Comparable<Building>{
10+
int h;
11+
boolean deleted;
12+
Building(int h) {
13+
this.h = h;
14+
this.deleted = false;
15+
}
16+
17+
18+
public int compareTo(Building o) {
19+
return o.h - this.h;
20+
}
21+
}
22+
23+
class Event {
24+
List<Building> starts;
25+
List<Building> ends;
26+
27+
Event() {
28+
this.starts = new ArrayList<>();
29+
this.ends = new ArrayList<>();
30+
}
31+
}
32+
/**
33+
* @param buildings: A list of lists of integers
34+
* @return: Find the outline of those buildings
35+
*/
36+
public ArrayList<ArrayList<Integer>> buildingOutline(int[][] buildings) {
37+
SortedMap<Integer, Event> events = new TreeMap<>();
38+
for(int[] b: buildings) {
39+
Building building = new Building(b[2]);
40+
if(!events.containsKey(b[0])) events.put(b[0], new Event());
41+
events.get(b[0]).starts.add(building);
42+
if(!events.containsKey(b[1])) events.put(b[1], new Event());
43+
events.get(b[1]).ends.add(building);
44+
}
45+
46+
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
47+
PriorityQueue<Building> curHeap = new PriorityQueue<>();
48+
int curMaxHi = 0;
49+
int begin = 0;
50+
for(Map.Entry<Integer, Event> e: events.entrySet()) {
51+
for(Building building: e.getValue().starts)
52+
curHeap.add(building);
53+
for(Building building: e.getValue().ends)
54+
building.deleted = true;
55+
56+
while(curHeap.size() > 0 && curHeap.peek().deleted)
57+
curHeap.remove();
58+
59+
int newHi = 0;
60+
if(curHeap.size() > 0)
61+
newHi = curHeap.peek().h;
62+
if(newHi != curMaxHi) {
63+
if(curMaxHi != 0) {
64+
ArrayList<Integer> r = new ArrayList<>();
65+
r.add(begin); r.add(e.getKey()); r.add(curMaxHi);
66+
ret.add(r);
67+
}
68+
begin = e.getKey();
69+
curMaxHi = newHi;
70+
}
71+
}
72+
return ret;
73+
}
74+
public static void main(String[] args) {
75+
int[][] buildings = new int[][] {
76+
{1, 3, 3},
77+
{2, 4, 4},
78+
{5, 6, 1}
79+
};
80+
System.out.println(new Solution().buildingOutline(buildings));
81+
}
82+
}
83+

0 commit comments

Comments
 (0)