题目链接:
LeetCode 56 — Merge Intervals
AC代码:
class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
@Override
public String toString() {
// TODO Auto-generated method stub
return "["+start+","+end+"]";
}
}
public class Problem56 {
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if(o1.start>o2.start)
return 1;
else if(o1.start<o2.start)
return -1;
else{
return 0;
}
}
});
int i=0;
while(true){
if(i+1>=intervals.size()) break;
else{
if(intervals.get(i+1).start>intervals.get(i).end){
i++;
continue;
}
else if(intervals.get(i+1).start==intervals.get(i).end){
intervals.get(i).end=intervals.get(i+1).end;
intervals.remove(i+1);
continue;
}
else{
if(intervals.get(i+1).end>=intervals.get(i).end){
intervals.get(i).end=intervals.get(i+1).end;
intervals.remove(i+1);
continue;
}
else{
intervals.remove(i+1);
}
}
}
}
return intervals;
}
}