https://leetcode.com/problems/the-skyline-problem/
class Solution {
class Point {
int x, y,s;
Point(int x, int y, int s) {
this.x = x;
this.y = y;
this.s = s;
}
// @Override
// public boolean equals(Object o) {
// Point c = (Point) o;
// return Integer.compare(y, c.y) == 0;
// }
}
Queue<Integer> pq = new PriorityQueue<>((a,b) -> b - a); // sort by y
List<Point> pointlist = new ArrayList<>();
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> list = new ArrayList<>();
if (buildings == null || buildings.length == 0|| buildings[0] == null || buildings[0].length == 0) return list;
//add point (x,y,s) to pointlist start s:0 end s:1
for (int[] building: buildings) {
Point p1 = new Point(building[0],building[2], 0);
Point p2 = new Point(building[1],building[2], 1);
pointlist.add(p1);
pointlist.add(p2);
}
Collections.sort(pointlist,(a,b)-> a.x-b.x);// sort by x
int prevh = 0;
pq.offer(0);//*!
int curx = pointlist.get(0).x;// initial x
int index = 0; // index++ only when at same x, otherwise need to generate ans
while (index < pointlist.size()) {
Point p = pointlist.get(index);
if (p.x == curx) {
if (p.s == 0) {
pq.offer(p.y);
} else {
pq.remove(p.y);
}
index++;
} else { //move to next x then generate ans
int curh = pq.peek();
//System.out.println(cur);
if (curh != prevh) {
int[] ans = new int[] {curx, curh};
prevh = curh;
list.add(ans);
}
curx = p.x;
}
}
//add last one
int[] ans = new int[] {curx, 0};
list.add(ans);
return list;
}
}