趣味算法题-1

1.在一维坐标轴上有n个区间段(坐标),求重合区间最长的两个区间段

1.先按有坐标排序。

2.用递归算法解决从后往前找长度。

public class point { //定义点类
	int x;
	int y;

	public point() {
		// TODO Auto-generated constructor stub
	}
	public point(int x, int y)
	{
		this.x = x;
		this.y = y;
	}

}
public static point comSegment(point p1, point p2)//求两个点是否相交,相交的话求相交的起点和终点
	{
		point comPoint = new point();
		if(p1.y < p2.x)
		{
			comPoint.x = 0;
			comPoint.y = 0;
		}
		else
		{
			comPoint.x = p2.x;
			comPoint.y = p1.y;
		}
		return comPoint;
	}
	public static int findMaxLen(ArrayList<point> p, int size, point maxPoint)//递归,动态规划
	{
		if(size < 0)
			return 0;
		if(size == 1)
		{
			maxPoint.x = p.get(0).x;
			maxPoint.y = p.get(0).y;
		}
		if(size == 2)
		{
			point com = comSegment(p.get(0), p.get(1));
			maxPoint.x = com.x;
			maxPoint.y = com.y;
		}
		int maxLen, tempLen;
		point tempPoint = new point();
		maxLen = findMaxLen(p, size-1, tempPoint);
		maxPoint = tempPoint;
		for(int i = 0; i < size-1; i++)
		{
			point com = comSegment(p.get(i), p.get(size-1));
			tempLen = com.y - com.x;
			if(tempLen > maxLen)
			{
				maxLen = tempLen;
				maxPoint = com;
			}
		}
		return maxPoint.y - maxPoint.x;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		point p1 = new point(1,5);
		point p2 = new point(2, 6);
		point p3 = new point(4,7);
		ArrayList<point> list = new ArrayList<point>();
		list.add(p1);
		list.add(p2);
		list.add(p3);
		Collections.sort(list, new Comparator<point>(){
			public int compare(point p1, point p2)
			{
				return p1.y - p2.y;
			}
		});
		point maxPoint = new point();
		int len = findMaxLen(list, list.size(), maxPoint);
		System.out.println(len);

	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值