Given a collection of intervals, merge all overlapping intervals.
/**
* 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 Solution {
public List<Interval> merge(List<Interval> intervals) {
List<Interval> res = new ArrayList<>();
if (intervals == null || intervals.size() == 0) {
return res;
}
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval i1, Interval i2) {
return i1.start - i2.start;
}
});
Interval preInterval = null;
for (Interval curInterval : intervals) {
if (preInterval == null || preInterval.end < curInterval.start) {
res.add(curInterval);
preInterval = curInterval;
}
else if (preInterval.end < curInterval.end) {
preInterval.end = curInterval.end;
}
}
return res;
}
}
3. Time & Space Complexity