Implementation
/**
* 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; }
* }
*/
class MyComparator implements Comparator<Interval> {
public int compare(Interval in1, Interval in2) {
return in1.start - in2.start;
}
}
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new MyComparator());
List<Interval> result = new ArrayList<Interval>();
Interval pre = null;
for (Interval interval: intervals) {
if (pre == null || pre.end < interval.start) {
result.add(interval);
pre = interval;
}
else {
if (interval.end > pre.end) {
pre.end = interval.end;
}
}
}
return result;
}
}
public class Solution {
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new MyComparator());
List<Interval> result = new ArrayList<Interval>();
for (int i = 0; i < intervals.size(); i++) {
if (result.isEmpty()) {
result.add(intervals.get(i));
}
else {
Interval pre = result.get(result.size() - 1);
Interval current = intervals.get(i);
if (pre.end < current.start) {
result.add(current);
}
else if (pre.end <= current.end) {
pre.end = current.end;
}
}
}
return result;
}
}