File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(n)
2+ // must retrieve all elements
3+ // SC: O(n)
4+ // need the same size of memory space in the worst case
5+ class Solution {
6+ public int [][] insert (int [][] intervals , int [] newInterval ) {
7+ List <int []> output = new ArrayList <>();
8+
9+ int i = 0 ;
10+ int n = intervals .length ;
11+
12+ while (i < n && intervals [i ][1 ] < newInterval [0 ]) {
13+ output .add (intervals [i ]);
14+ i += 1 ;
15+ }
16+
17+ while (i < n && intervals [i ][0 ] <= newInterval [1 ]) {
18+ newInterval [0 ] = Math .min (newInterval [0 ], intervals [i ][0 ]);
19+ newInterval [1 ] = Math .max (newInterval [1 ], intervals [i ][1 ]);
20+ i += 1 ;
21+ }
22+
23+ output .add (newInterval );
24+
25+ while (i < n ) {
26+ output .add (intervals [i ]);
27+ i += 1 ;
28+ }
29+
30+ return output .toArray (new int [output .size ()][]);
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments