-
Notifications
You must be signed in to change notification settings - Fork 1
/
insert-interval-1.java
36 lines (33 loc) · 1.06 KB
/
insert-interval-1.java
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
28
29
30
31
32
33
34
35
36
/**
* 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> insert(List<Interval> intervals, Interval newInterval) {
intervals.add(newInterval);
Collections.sort(intervals, new Comparator<Interval>(){
@Override
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
List<Interval> results = new ArrayList<>();
int start = intervals.get(0).start, end = intervals.get(0).end;
for (Interval interval: intervals) {
if (interval.start > end) {
results.add(new Interval(start, end));
start = interval.start;
end = interval.end;
} else {
end = Math.max(end, interval.end);
}
}
results.add(new Interval(start, end));
return results;
}
}