62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class CSDN {
@SuppressWarnings("unchecked")
public void test(){
int sum = 0;
int numOfStart = 1;
int numOfEnd = 0;
ArrayList<Line> ls = new ArrayList<Line>();
ls.add(new Line(2,6));
ls.add(new Line(3,10));
ls.add(new Line(7,13));
MyPoint[] array = new MyPoint[ls.size()*2];
for(int i=0;i<ls.size();i++){
Line l = ls.get(i);
array[i*2] = new MyPoint(l.start,"s");
array[i*2+1] = new MyPoint(l.end,"e");
}
Arrays.sort(array,new MyComparator());
for(int i=0;i<array.length-1;i++){
if(array[i].type.equals("e")&&array[i+1].type.equals("s")&&numOfStart==numOfEnd){
//do nothing
}
else{
sum += array[i+1].num - array[i].num;
}
if(array[i+1].type.equals("s")){
numOfStart = numOfStart+1;
}
else{
numOfEnd = numOfEnd+1;
}
}
System.out.println("sum:"+sum);
}
class MyPoint{
MyPoint(int num,String type){
this.num = num;
this.type = type;
}
int num;
String type;
}
class Line{
Line(int start,int end){
this.start = start;
this.end = end;
}
int start;
int end;
}
@SuppressWarnings("unchecked")
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
MyPoint p1 = (MyPoint)o1;
MyPoint p2 = (MyPoint)o2;
return p1.num==p2.num?-(p1.type.compareTo(p2.type)):(p1.num<p2.num?-1:1);
}
}
public static void main(String[] args){
CSDN csdn = new CSDN();
csdn.test();
}
}
import java.util.ArrayList;
import java.util.Collections;
public class TestLine {
public static int addLine(ArrayList<Line> lines){
if(lines.size()==0){
return 0;
}
//将所有线段根据起始端点进行排列
Collections.sort(lines);
//记录当前线段总长度
int sumLength =lines.get(0).getLength();
//记录当前记录的末点
int endIndex = lines.get(0).getEnd();
for(int i =1;i<lines.size();i++){
Line line = lines.get(i);
if(line.getStart()>=endIndex){
//这条线段和前面的线段不相交
sumLength +=line.getLength();
endIndex = line.getEnd();
}else if(line.getStart()<endIndex&&line.getEnd()>=endIndex){
//这条线段和前面的重合一部分
sumLength +=line.getEnd()-endIndex;
endIndex = line.getEnd();
}else if(line.getEnd()<endIndex){
/*
* 这条线段被包含在前面的线段里面,不做任何事
* 仅是方便注释,可以删除该项
*/
}
}
return sumLength;
}
public static void main(String[] args) {
Line line1 = new Line(2,6);
Line line2 = new Line(3,7);
Line line3 = new Line(7,13);
ArrayList<Line> list= new ArrayList<Line>();
list.add(line1);
list.add(line2);
list.add(line3);
System.out.println(addLine(list));
}
}
class Line implements Comparable<Line>{
private int start;
private int end;
private int length;
public Line(int start,int end){
this.start=start;
this.end = end;
this.length = end-start;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
//让sort方法根据起始端点进行比较
@Override
public int compareTo(Line line) {
return this.start-line.start;
}
}
输出结果:11