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);
}