http://lintcode.com/zh-cn/problem/building-outline/
水平面上有 N 座大楼,每座大楼都是矩阵的形状,可以用一个三元组表示 (start, end, height)
,分别代表其在x轴上的起点,终点和高度。大楼之间从远处看可能会重叠,求出 N 座大楼的外轮廓线。
外轮廓线的表示方法为若干三元组,每个三元组包含三个数字 (start, end, height),代表这段轮廓的起始位置,终止位置和高度。
请注意合并同样高度的相邻轮廓,不同的轮廓线在x轴上不能有重叠。
您在真实的面试中是否遇到过这个题?
是
样例
给出三座大楼:
[
[1, 3, 3],
[2, 4, 4],
[5, 6, 1]
]
外轮廓线为:
[
[1, 2, 3],
[2, 4, 4],
[5, 6, 1]
]
来,上大餐:没啥可想,1化2,比较器+存储
public class zzzk_building {
public static class Node {
public boolean UPIS;
public int H;
public int w;
public Node(int w, int H, boolean UPIS) {
this.UPIS = UPIS;
this.H = H;
this.w = w;
}
}
public static class NodeComparator implements Comparator<Node> {
public int compare(Node o1, Node o2) {
if (o1.w != o2.w) {
return o1.w - o2.w;
}
if (o1.UPIS != o2.UPIS) {
return o1.UPIS ? -1 : 1;
}
return 0;
}
}
public static List<List<Integer>> building(int[][] building) {
Node[] nodes = new Node[building.length * 2];
for (int i = 0; i < building.length; i++) {
nodes[i * 2] = new Node(building[i][0], building[i][2], true);
nodes[i * 2 + 1] = new Node(building[i][1], building[i][2], false);
}
Arrays.sort(nodes, new NodeComparator());
TreeMap<Integer, Integer> htmap = new TreeMap<Integer, Integer>();
TreeMap<Integer, Integer> wtmap = new TreeMap<Integer, Integer>();
for (int i = 0; i < nodes.length; i++) {
if (nodes[i].UPIS) {
if (!htmap.containsKey(nodes[i].H)) {
htmap.put(nodes[i].H, 1);
} else {
htmap.put(nodes[i].H, htmap.get(nodes[i].H) + 1);
}
} else {
if (htmap.containsKey(nodes[i].H)) {
if (htmap.get(nodes[i].H) == 1) {
htmap.remove(nodes[i].H);
} else {
htmap.put(nodes[i].H, htmap.get(nodes[i].H) - 1);
}
}
}
if (htmap.isEmpty()) {
wtmap.put(nodes[i].w, 0);
} else {
wtmap.put(nodes[i].w, htmap.lastKey());
}
}
//泛式取代强制转换
List<List<Integer>> res = new ArrayList<List<Integer>>();
int start = 0;
int height = 0;
for (Entry<Integer, Integer> entry : wtmap.entrySet()) {
int curw = entry.getKey();
int curh = entry.getValue();
if (height != curh) {
if (height != 0) {
List<Integer> newone = new ArrayList<Integer>();
newone.add(start);
newone.add(curw);
newone.add(curh);
res.add(newone);
}
start = curw;
height = curh;
}
}
return res;
}
}