题目
定义一个表示起止属性的类
public class Interval {
int start;
int end;
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 Interval ( ) {
this . start = 0 ;
this . end = 0 ;
}
public Interval ( int start, int end) {
this . start = start;
this . end = end;
}
}
算法实现
static List < Interval > resultList = new ArrayList < Interval > ( ) ;
public static List < Interval > meagerInterval ( List < Interval > list) {
Collections . sort ( list, ( ( o1, o2) -> o1. start - o2. start) ) ;
for ( int i = 0 ; i < list. size ( ) ; i++ ) {
int start = list. get ( i) . start;
int end = list. get ( i) . end;
int j = i + 1 ;
while ( j < list. size ( ) && end >= list. get ( j) . start) {
end = Math . max ( end, list. get ( j) . end) ;
j++ ;
}
i = j - 1 ;
resultList. add ( new Interval ( start, end) ) ;
}
return resultList;
}