LeetCode The Skyline Problem

原题链接在这里:https://leetcode.com/problems/the-skyline-problem/

发现result里的点都是高度出现落差时出现的。

把input 拆成左节点横坐标与高,右节点很坐标与高,为了区分,右节点的高设成负值。都插入verti List里然后排序。

从前往后扫verti, 遇到左边就把其高度存入大堆里,更新cur 为最大高,遇到右边就把对应左边拿出,更新cur = maxHeap.isEmpty() ? 0 : maxHeap.peek().

每当 当前最大高度cur 与之前最大高度 pre不同时,就吧{temp[0], cur} 存入res中去。

AC Java:

 1 public class Solution {
 2     public List<int[]> getSkyline(int[][] buildings) {
 3         List<int []> res = new ArrayList<int []>();
 4         
 5         PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
 6         List<int []> verti = new ArrayList<int []>();
 7         for(int i = 0; i<buildings.length; i++){
 8             int [] temp = buildings[i];
 9             verti.add(new int [] {temp[0], temp[2]}); //左边界
10             verti.add(new int [] {temp[1], -temp[2]});//右边界,高度存成负数以便区分
11         }
12         Collections.sort(verti,new arrayCom());
13         
14         int cur = 0; //当前最大高度
15         int pre = 0; //之前最大高度
16         for(int i = 0; i<verti.size(); i++){
17             int [] temp = verti.get(i);
18             if(temp[1] > 0){        //左边界
19                 maxHeap.offer(temp[1]);     //高度入队
20                 cur = maxHeap.peek();       //当前最高
21             }else{
22                 maxHeap.remove(-temp[1]);
23                 cur = maxHeap.isEmpty() ? 0 : maxHeap.peek();
24             }
25             if(cur != pre){
26                 res.add(new int [] {temp[0], cur});
27                 pre = cur;
28             }
29         }
30         return res;
31     }
32 }
33 
34 class arrayCom implements Comparator<int []>{
35     public int compare(int [] a1, int [] a2){
36         if(a1[0] == a2[0]){
37             return a2[1] - a1[1];
38         }
39         return a1[0] - a2[0];
40     }
41 }

 

你可能感兴趣的:(LeetCode The Skyline Problem)