Skip to content

Commit 5f8f28e

Browse files
committed
Time: 1 ms (98.50%), Space: 44.8 MB (25.09%) - LeetHub
1 parent 7be9d2a commit 5f8f28e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// produce a new int[][] with newInterval inserted; the intervals is already sorted by start_i; the given interval is non-overlapping; the return interval does not have to be sorted;
2+
3+
// method: loop throught the entire intervals; compare the start and end points, then merge;
4+
5+
class Solution {
6+
public int[][] insert(int[][] intervals, int[] newInterval) {
7+
8+
// init an res list: list of 2d array
9+
List<int[]> res = new ArrayList<>();
10+
11+
// loop through the array; and check endpoints conditions
12+
for (int i=0; i<intervals.length; i++) {
13+
14+
int[] currInterval = intervals[i];
15+
16+
// if the interval starts before currInterval
17+
if (newInterval[1] < currInterval[0]) {
18+
19+
res.add(newInterval);
20+
newInterval = currInterval;
21+
}
22+
// if newInterval happens after the currInterval
23+
else if (newInterval[0] > currInterval[1]) {
24+
25+
res.add(currInterval);
26+
27+
} else {
28+
29+
// take the min. of 2 start point, and max. of 2 end point:
30+
newInterval[0] = Math.min(newInterval[0], currInterval[0]);
31+
newInterval[1] = Math.max(newInterval[1], currInterval[1]);
32+
}
33+
}
34+
35+
res.add(newInterval);
36+
37+
return res.toArray(new int[res.size()][]);
38+
}
39+
}

0 commit comments

Comments
 (0)