您的位置:首页 > 其它

[LeetCode]218. The Skyline Problem

2017-02-24 18:48 375 查看
https://leetcode.com/problems/the-skyline-problem/?tab=Description

由图片一转成图片二,输入是每个建筑左右边坐标以及高度[L, R, H]





将每个建筑左上和右上两个顶点抽出来排序,高度为负的是左顶点为正的是右顶点,然后过一遍treemap,遇到左顶点加入,遇到右顶点移除,如果当前高度与前一高度不同,那么当前顶点及treemap的当前最大高度即为所求一点

public class Solution {
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> res = new LinkedList();
List<int[]> height = new LinkedList();
for (int[] building : buildings) {
height.add(new int[]{building[0], -building[2]});
height.add(new int[]{building[1], building[2]});
}
Collections.sort(height, new Comparator<int[]>() {
public int compare(int[] i1, int[] i2) {
if (i1[0] == i2[0]) {
return i1[1] - i2[1];
} else {
return i1[0] - i2[0];
}
}
});
int prev = 0;
TreeMap<Integer, Integer> map = new TreeMap(new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return i2 - i1;
}
});
map.put(0, 1);
for (int[] h : height) {
if (h[1] < 0) {
map.put(-h[1], map.getOrDefault(-h[1], 0) + 1);
} else {
Integer cnt = map.get(h[1]);
if (cnt == 1) {
map.remove(h[1]);
} else {
map.put(h[1], map.get(h[1]) - 1);
}
}
int cur = map.firstKey();
if (cur != prev) {
res.add(new int[]{h[0], cur});
prev = cur;
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: