Check the comments
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> res = new ArrayList<Interval>();
int i=0;
//Add all the interval before the overlapping
for (; i<intervals.size() && newInterval.start > intervals.get(i).end; i++) {
res.add(intervals.get(i));
}
//Add the overlapping interval (Find the last overlapping interval)
for (; i<intervals.size() && intervals.get(i).start<= newInterval.end; i++) {
newInterval.start = Math.min(newInterval.start, intervals.get(i).start);
newInterval.end = Math.max(newInterval.end, intervals.get(i).end);
}
res.add(newInterval);
//Add all the interval after the overlapping
for (; i<intervals.size(); i++) {
res.add(intervals.get(i));
}
return res;
}
No comments:
Post a Comment