编辑代码

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Comparator;
class Main {
	public static void main(String[] args) {
		SectionTemplate sectionTemplate=new SectionTemplate();
        sectionTemplate.t01();
        sectionTemplate.t02();
        sectionTemplate.t03();
	}
}

class Section {
   public int start;
   public int end;
    Section(int start,  int end) {
       this.start=start;
       this.end=end;
    }
    Section(Section section) {
        this.start=section.start;
        this.end=section.end;
    }
}

class SectionTemplate {
    public static LinkedList<Section> findSection(Section[] sections){
        LinkedList<Section> beans = new LinkedList<Section>();
        Arrays.sort(sections, new Comparator<Section>() {
            public int compare(Section o1, Section o2) {
                if (o1.end < o2.end){
                    return -1;
                }
                else if (o1.end == o1.end) {
                    return 0;
                }
                else {
                    return 1;
                }
            }
        });
        beans.add(sections[0]);
        for (int i = 1; i < sections.length; i++) {
            Section last = beans.getLast();
            if (last.end <= sections[i].start) {
               beans.add(sections[i]);
            }
        }
        return beans;
    }

    public static void t01() {
        Section[] sections = {
                new Section(1, 2),
                new Section(2, 3),
                new Section(3, 4)
        };
        LinkedList<Section> beans = findSection(sections);
        double maxValue = 0;
        System.out.println("\n不相交的区间为:");
        for (int i = 0; i < beans.size(); ++i) {
            System.out.println("(" + beans.get(i).start + "," + beans.get(i).end + ")");
        }
    }

    public static void t02() {
        Section[] sections = {
                new Section(1, 2),
                new Section(1, 3),
                new Section(1, 4),
                new Section(1, 5)
        };
        LinkedList<Section> beans = findSection(sections);
        double maxValue = 0;
        System.out.println("\n不相交的区间为:");
        for (int i = 0; i < beans.size(); ++i) {
            System.out.println("(" + beans.get(i).start + "," + beans.get(i).end + ")");
        }
    }

    public static void t03() {
        Section[] sections = {
                new Section(3, 1),
                new Section(1, 3),
                new Section(1, 5),
                new Section(5, 1),
                new Section(3, 3)

        };
        LinkedList<Section> beans = findSection(sections);
        double maxValue = 0;
        System.out.println("\n不相交的区间为:");
        for (int i = 0; i < beans.size(); ++i) {
            System.out.println("(" + beans.get(i).start + "," + beans.get(i).end + ")");
        }

    }
}