Note:

1. There is a trick here: As it only gets the starting point, we can check each bound of the building. Also we have to have a "sign" to know when the bound is start when the bound is end.

2. REMEMBER to add 0 to the queue to avoid NPE. Also 0 represents there is no building there.

class Solution {
    public List<int[]> getSkyline(int[][] buildings) {
        if (buildings.length == 0) {
            return new ArrayList<>();
        }
        
        List<int[]> result = new ArrayList<>();
        List<int[]> height = new ArrayList<>();
        for (int[] building : buildings) {
            height.add(new int[]{building[0], -building[2]});
            height.add(new int[]{building[1], building[2]});
        }
        
        Collections.sort(height, (b1, b2) -> {return b1[0] == b2[0] ? b1[1] - b2[1] : b1[0] - b2[0];});
        PriorityQueue<Integer> queue = new PriorityQueue<>((i1, i2) -> (i2 - i1));
        queue.offer(0);
        int prev = 0;
        for (int[] vertical : height) {
            if (vertical[1] < 0) {
                queue.offer(-vertical[1]);
            } else {
                queue.remove(vertical[1]);
            }
            
            int current = queue.peek();
            if (prev != current) {
                result.add(new int[]{vertical[0], current});
                prev = current;
            }
        }
        return result;
    }
}

 

posted on 2017-09-04 14:04  keepshuatishuati  阅读(135)  评论(0编辑  收藏  举报