这个题,先定义一个comparator,定义了comparator需要重写compare函数。 然后用两个interval比较第i-1个的end和第i个的start,如果第i-1个end大于等于第i个start,overlap第i个interval,否则没有overlap,直接存到result里面。
搞个小插曲: comparable 和comparator的区别,简单记两个都可以比较自定义的两个object。comparator是利用strategy design pattern来完成比较,并且可以实现sort功能。所以这个题我们用到了comparator,写了一个内部类。
另外Comparator 自己定义compare方法。
comparable定义的是compareTo方法
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<Interval> result = new ArrayList<Interval>();
if(intervals == null || intervals.isEmpty()) return result;
//define the comparator
Comparator<Interval> comparator = new Comparator<Interval>(){
public int compare(Interval i1, Interval i2){
if(i1.start < i2.start) return -1;
else if(i1.start > i2.start) return 1;
else{
if(i1.end < i2.end) return -1;
else if(i1.end > i2.end) return 1;
else return 0;
}
}
};
Collections.sort(intervals, comparator);
//compare the intervals
for(int i=0; i<intervals.size();i++){
Interval curr = intervals.get(i);
if(result.isEmpty()){
result.add(curr);
}else{
Interval last = result.get(result.size()-1);
if(last.end >= curr.start){
last.end = Math.max(last.end, curr.end);
}else{
result.add(curr);
}
}
}
return result;
}
No comments:
Post a Comment