File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .ArrayList ;
2
+ import java .util .Arrays ;
3
+ import java .util .Comparator ;
4
+ import java .util .List ;
5
+
6
+ class Solution {
7
+
8
+ public int [][] merge (int [][] intervals ) {
9
+ // TC: O(N log N)
10
+ // SC: O(N)
11
+
12
+ // length가 2보다 적으면 그대로 반환
13
+ if (intervals .length < 2 ) {
14
+ return intervals ;
15
+ }
16
+
17
+ List <int []> output = new ArrayList <>();
18
+
19
+ // intervals 배열을 시작 시간 기준으로 정렬
20
+ Arrays .sort (intervals , Comparator .comparingInt (a -> a [0 ]));
21
+
22
+ for (int [] interval : intervals ) {
23
+ // output이 비어있거나, 현재 interval이 마지막에 추가된 구간과 겹치지 않으면 추가
24
+ if (output .isEmpty () || output .get (output .size () - 1 )[1 ] < interval [0 ]) {
25
+ output .add (interval );
26
+ } else {
27
+ // 겹치는 경우, 마지막 구간의 끝 시간을 업데이트
28
+ output .get (output .size () - 1 )[1 ] = Math .max (output .get (output .size () - 1 )[1 ], interval [1 ]);
29
+ }
30
+ }
31
+
32
+ // List<int[]>를 int[][] 배열로 변환하여 반환
33
+ return output .toArray (new int [output .size ()][]);
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments