package homework;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
public class Section {
public static LinkedList<SectionItem> findUncrossedSections(SectionItem[] sections) {
LinkedList<SectionItem> uncrossedSections = new LinkedList<>();
Arrays.sort(sections, Comparator.comparingInt(left -> left.end));
uncrossedSections.add(sections[0]);
for (int i = 1; i < sections.length; i++) {
SectionItem last = uncrossedSections.getLast();
if (last.end <= sections[i].start) {
uncrossedSections.add(sections[i]);
}
}
return uncrossedSections;
}
public static void main(String[] args) {
SectionItem[] sections = {
new SectionItem(6, 8),
new SectionItem(2, 4),
new SectionItem(3, 5),
new SectionItem(1, 5),
new SectionItem(5, 9),
new SectionItem(8, 10),
new SectionItem(5, 7),
new SectionItem(7, 9),
new SectionItem(9, 10)
};
LinkedList<SectionItem> uncrossedSections = findUncrossedSections(sections);
System.out.println("找到如下不相交的区间:");
for (SectionItem section : uncrossedSections) {
System.out.println("(" + section.start + "," + section.end + ")");
}
}
}
class SectionItem {
public int start;
public int end;
public SectionItem(int start, int end) {
this.start = start;
this.end = end;
}
}