用Collections.sort方法对list排序,根据Collections.sort重载方法来实现:
本题是leetcode56. Merge Intervals
<span style="font-size:14px;">public class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}</span>
<span style="font-size:14px;"></span><pre name="code" class="java">public List<Interval> merge(List<Interval> intervals) {
ArrayList<Interval> list = new ArrayList<Interval>();
if(intervals == null || intervals.size() == 0)
return list;
if(intervals.size() == 1){
list.add(intervals.get(0));
return list;
}
//需要先排序
//myComparator cc = new myComparator();
//intervals.sort(cc);
//Collections.sort(intervals, cc);
// Sort by ascending starting point using an anonymous Comparator
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
return Integer.compare(i1.start, i2.start);
}
});
list.add(intervals.get(0));
for(int i=1;i<intervals.size();i++){
if(list.get(list.size()-1).end >= intervals.get(i).start){//进行合并
Interval tmp = list.remove(list.size()-1);
tmp.end = Math.max(tmp.end,intervals.get(i).end);
list.add(tmp);
}
else
list.add(intervals.get(i));
}
return list;
}
参考链接:http://blog.csdn.net/zxy_snow/article/details/7232035