-
Notifications
You must be signed in to change notification settings - Fork 6
/
InsertInterval.java
36 lines (28 loc) · 1001 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
import java.util.ArrayList;
import java.util.List;
/**
* Created by achoudhary on 03/02/2016.
*/
class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}
public class InsertInterval {
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
ArrayList<Interval> result = new ArrayList<Interval>();
for(Interval interval: intervals){
if(interval.end < newInterval.start){
result.add(interval);
}else if(interval.start > newInterval.end){
result.add(newInterval);
newInterval = interval;
}else if(interval.end >= newInterval.start || interval.start <= newInterval.end){
newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end));
}
}
result.add(newInterval);
return result;
}
}