leetcode 56. Merge Intervals
这一题思路笔记简单,先采用容器对list进行升序排序,然后在逐一合并前后的区间。需要注意的地方有Comparator 比较器容器的写法,实现Comparator的接口,compare函数重写返回值要注意有三个。0 -1 1 return o1-o2 升序排列。
public class Solution {
class mycmp implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Interval Into1 = (Interval)o1;
Interval Into2 = (Interval)o2;
if(Into1.start < Into2.start){
return -1;
}else if(Into1.start > Into2.start){
return 1;
}else{
return 0;
}
}
}
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res = new ArrayList<Interval>();
int len = intervals.size();
if(len==0) return res;
Comparator cmp = new mycmp();
Collections.sort(intervals,cmp);
int pre_s = intervals.get(0).start;
int pre_e = intervals.get(0).end;
for(int i=1;i<len;i++){
Interval inter = intervals.get(i);
int cur_s = inter.start;
int cur_e = inter.end;
if(cur_s<=pre_e&&cur_e>pre_e){
pre_e = cur_e;
}else if(cur_s>pre_e){
Interval new_in = new Interval(pre_s,pre_e);
res.add(new_in);
pre_s = cur_s;
pre_e = cur_e;
}
}
Interval new_in = new Interval(pre_s,pre_e);
res.add(new_in);
return res;
}
}