-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathinsertInterval.java
35 lines (33 loc) · 1011 Bytes
/
insertInterval.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
/**
* 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) {
List<Interval> result = new ArrayList<>();
for(Interval iter:intervals)
{
if(newInterval == null || iter.end < newInterval.start)
result.add(iter);
else if(iter.start > newInterval.end)
{
result.add(newInterval);
result.add(iter);
newInterval = null;
}
else
{
newInterval.start = Math.min(newInterval.start, iter.start);
newInterval.end = Math.max(newInterval.end, iter.end);
}
}
if(newInterval != null)
result.add(newInterval);
return result;
}
}