057.Insert Interval

Solution 1: accepted 21ms

Add the new node to the list, and do the rest just like 056.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> result = new ArrayList<>();
intervals.add(newInterval);
if (intervals.size() == 1)
return intervals;
Collections.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
for (int i = 0; i < intervals.size() - 1; i++) {
Interval current = intervals.get(i);
Interval next = intervals.get(i + 1);
if (current.end < next.start) {
result.add(current);
} else {
next.start = current.start;
next.end = Math.max(current.end, next.end);
}
}
result.add(intervals.get(intervals.size() - 1));
return result;
}