Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 18, 2016 02:05
Show Gist options
  • Save cangoal/483cf4a5c21ad95d93970e0057aba6f2 to your computer and use it in GitHub Desktop.
Save cangoal/483cf4a5c21ad95d93970e0057aba6f2 to your computer and use it in GitHub Desktop.
LeetCode - The Skyline Problem
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> res = new ArrayList<int[]>();
List<int[]> heights = new ArrayList<int[]>();
for(int[] building : buildings){
heights.add(new int[]{building[0], -building[2]});
heights.add(new int[]{building[1], building[2]});
}
Collections.sort(heights, (a, b) ->{
if(a[0] != b[0])
return a[0] - b[0];
return a[1] - b[1];
});
Queue<Integer> queue = new PriorityQueue<Integer>((a, b) -> (b - a));
queue.offer(0);
int prev = 0;
for(int[] h : heights){
if(h[1] < 0){
queue.offer(-h[1]);
} else {
queue.remove(h[1]);
}
int cur = queue.peek();
if(prev != cur){
res.add(new int[]{h[0], cur});
prev = cur;
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment