-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertInterval.java
More file actions
32 lines (30 loc) · 959 Bytes
/
InsertInterval.java
File metadata and controls
32 lines (30 loc) · 959 Bytes
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
package mergeIntervals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class InsertInterval {
public List<Interval> insert(List<Interval> intervals, Interval newInterval){
List<Interval> result = new ArrayList<>();
if(intervals.isEmpty()){
result.add(newInterval);
return result;
}
int[] start = new int[intervals.size()+1];
int[] end = new int[intervals.size()+1];
for(int i = 0; i < intervals.size(); i++){
start[i] = intervals.get(i).start;
end[i] = intervals.get(i).end;
}
start[intervals.size()] = newInterval.start;
end[intervals.size()] = newInterval.end;
Arrays.sort(start);
Arrays.sort(end);
for (int i = 0, j = 0; i < intervals.size()+1; i++) { // j is start of interval.
if (i == intervals.size() - 1 || start[i + 1] > end[i]) {
result.add(new Interval(start[j], end[i]));
j = i + 1;
}
}
return result;
}
}