forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertIntervals.java
More file actions
38 lines (31 loc) · 938 Bytes
/
InsertIntervals.java
File metadata and controls
38 lines (31 loc) · 938 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
33
34
35
36
37
38
// Space and time => o(n)
class InsertIntervals {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> ans = new LinkedList<>();
int i=0;
int len = intervals.length;
// safe intervals before merging
while(i<len && intervals[i][1]< newInterval[0]){
ans.add(intervals[i]);
i++;
}
// merging part
while(i<len && intervals[i][0] <= newInterval[1]){
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
ans.add(newInterval);
while(i<len){
ans.add(intervals[i]);
i++;
}
int[][] result = new int[ans.size()][2];
int j=0;
while(j<ans.size()){
result[j] = ans.get(j);
j++;
}
return result;
}
}