算法之楼轮廓问题(Java)

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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值