区间不相交问题:给出N个开区间,从中选择尽可能多的开区间,使得这些开区间两两没有交集。如(1,3) (2,4) (3,5) (6,7),结果应为(1,3) (3,5) (6,7)
package PAT;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class IntervalGreed{
//(1,3) (2,4) (3,5) (6,7)
//输入示例
//4
//1 3 2 4 3 5 6 7
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
if (N<=0) return;
ArrayList<Interval> intervals = new ArrayList<>();
for (int i = 0; i < N; i++) {
intervals.add(new Interval(scanner.nextInt(),scanner.nextInt()));
}
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if (o1.x!=o2.x){
return o2.x-o1.x;
}else {
return o1.y-o2.y;
}
}
});
//输出选择的区间
System.out.println(intervals.get(0).x+" "+intervals.get(0).y);
int lastX=intervals.get(0).x;
for (int i = 1; i < N; i++) {
if (intervals.get(i).y<=lastX){
//闭区间此处改为intervals.get(i).y<lastX即可
System.out.println(intervals.get(i).x+" "+intervals.get(i).y);
lastX=intervals.get(i).x;
}
}
}
}
class Interval{
int x;
int y;
public Interval(int x, int y) {
this.x = x;
this.y = y;
}
}