File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(n log n)
2+ // It takes n log n to sort array, visit all elements in O(n) time, total O(n log n)
3+ // SC: O(n)
4+ // Needs max O(n) space to save intervals
5+ class Solution {
6+ public int [][] merge (int [][] intervals ) {
7+ int n = intervals .length ;
8+ if (n == 1 ) return intervals ;
9+
10+ Arrays .sort (intervals , (a , b ) -> Integer .compare (a [0 ], b [0 ]));
11+ List <int []> output = new ArrayList <>();
12+ output .add (intervals [0 ]);
13+
14+ int [] currentInterval = intervals [0 ];
15+
16+ for (int [] interval : intervals ) {
17+ int currentEnd = currentInterval [1 ];
18+ int nextStart = interval [0 ];
19+ int nextEnd = interval [1 ];
20+ if (currentEnd >= nextStart ) {
21+ currentInterval [1 ] = Math .max (currentEnd , nextEnd );
22+ } else {
23+ currentInterval = interval ;
24+ output .add (currentInterval );
25+ }
26+ }
27+
28+ return output .toArray (new int [output .size ()][]);
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments