For example,
Given
[1,3],[2,6],[8,10],[15,18]
,return
[1,6],[8,10],[15,18]
./**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if(intervals==null || intervals.size()==0) {
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b) {
if(a.start<b.start) {
return -1;
} else if(a.start>b.start) {
return 1;
} else {
return a.end - b.end;
}
}
});
ArrayList<Interval> newIns = new ArrayList<Interval>();
Interval tmp = intervals.get(0);
newIns.add(tmp);
for(int i=1;i<intervals.size();i++) {
Interval in = intervals.get(i);
if(in.start>tmp.end) {
newIns.add(in);
tmp = in;
} else if(in.end<=tmp.end) {
continue;
} else if(in.end>tmp.end){
tmp.end = in.end;
}
}
return newIns;
}
}
==========
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || intervals.size() == 0) {
return intervals;
}
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval i1, Interval i2) {
if (i1.start == i2.start) {
return i1.end - i2.end;
} else {
return i1.start - i2.start;
}
}
}
);
List<Interval> res = new ArrayList<Interval>();
Interval pre = new Interval(intervals.get(0).start, intervals.get(0).end);
for (int i = 1; i < intervals.size(); i++) {
Interval cur = intervals.get(i);
if (cur.start <= pre.end) {
pre.end = Math.max(pre.end, cur.end);
} else {
res.add(pre);
pre = new Interval(cur.start, cur.end);
}
}
res.add(pre);
return res;
}
}
没有评论:
发表评论