输出大楼轮廓线问题

在这里插入图片描述
分析一下
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

public static class Node{
		public boolean isUp;//记录是向上还是向下
		public int posi;//记录位置
		public int h;//记录高度
		
		public Node(boolean bORe,int position,int height)
		//布尔值true为上,false为下
		{
			isUp=bORe;
			posi=position;
			h=height;
		}
	}
	
	public static class NodeComparator implements Comparator<Node>{
		public int compare(Node o1,Node o2) {
			
		if(o1.posi!=o2.posi){		
		//位置不同,位置小的在前面
			return o1.posi-o2.posi;
		}		
		if(o1.isUp!=o2.isUp)
		//位置相同,升的位置在前面
		{
			return o1.isUp ? -1:1;
		}
		return 0;
	}
}
	
	public static List<List<Integer>> buildingOutlilne(int[][] buildings)
	{
		Node[] nodes=new Node[buildings.length*2];
		for(int i=0;i<buildings.length;i++)
		{
			nodes[i*2]=new Node(true,buildings[i][0],buildings[i][2]);
			//上,开始位置,高度
			nodes[i*2+1]=new Node(false,buildings[i][0],buildings[i][2]);
			//下,结束位置,高度
		}
		Arrays.sort(nodes, new NodeComparator());
		TreeMap<Integer,Integer> htMap=new TreeMap<>();
		//高度,次数
		TreeMap<Integer,Integer> pmMap=new TreeMap<>();
		for(int i=0;i<nodes.length;i++)
		{
			if(nodes[i].isUp)
				//如果上升
			{
				if(!htMap.containsKey(nodes[i].h)) {
					//不含有就是第一次出现
					htMap.put(nodes[i].h, 1);
				}else {
					//不是第一次就在以前次数上+1
					htMap.put(nodes[i].h,htMap.get(nodes[i].h)+1);
				}
			}
			//如果下降
			else {
				if(htMap.containsKey(nodes[i].h)) 
				//如果出现过
				{
					//出现过1次
					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()) {
				pmMap.put(nodes[i].posi, 0);
			}else {
				pmMap.put(nodes[i].posi, htMap.lastKey());
				//htMap的key是高度
			}
		}
		
		List<List<Integer>> res=new ArrayList<>();
		int start=0;
		int height=0;//之前的高度
		for (Entry<Integer,Integer>entry:pmMap.entrySet())
			//Entry是map下的方法,用来遍历map
		{
			int curPosition=entry.getKey();//当前位置
			int curMaxHeight=entry.getValue();//当前高度
			if(height!=curMaxHeight)//现在的高度!=以前的高度
			{
				if(height!=0) {//高度!=0
					List<Integer>newRecord=new ArrayList<Integer>();
					newRecord.add(start);//起始位置
					newRecord.add(curPosition);//结束位置
					newRecord.add(height);//高度
					res.add(newRecord);
				}
				start=curPosition;
				height=curMaxHeight;
			}
		}
		return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值