File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @link https://leetcode.com/problems/merge-intervals/
3
+ *
4
+ * 접근 방법 :
5
+ * - 인터벌 배열 첫 번째 요소 기준으로 오름차순 정렬
6
+ * - 인터벌의 시작이 이전 인터벌 끝보다 작으면 범위 업데이트
7
+ * - 범위에 속하지 않으면 현재 인터벌을 결과 배열에 추가하고 새로운 인터벌로 업데이트
8
+ *
9
+ * 시간복잡도 : O(nlogn)
10
+ * - n = 인터벌 배열의 길이
11
+ * - 인터벌 배열 정렬 : O(nlogn)
12
+ * - 병합 과정: O(n)
13
+ *
14
+ * 공간복잡도 : O(n)
15
+ * - 결과 배열에 담아서 리턴
16
+ */
17
+ function merge ( intervals : number [ ] [ ] ) : number [ ] [ ] {
18
+ const result : number [ ] [ ] = [ ] ;
19
+
20
+ if ( intervals . length < 2 ) return intervals ;
21
+
22
+ // 첫번째 요소 기준으로 정렬
23
+ const sortedIntervals = intervals . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
24
+
25
+ let [ start , end ] = sortedIntervals [ 0 ] ;
26
+
27
+ for ( let i = 1 ; i < sortedIntervals . length ; i ++ ) {
28
+ const [ newStart , newEnd ] = sortedIntervals [ i ] ;
29
+ if ( newStart <= end ) {
30
+ // 범위 겹치는 경우, end 업데이트
31
+ end = Math . max ( end , newEnd ) ;
32
+ } else {
33
+ // 겹치지 않는 경우, 현재 구간 추가하고 새로운 구간으로 업데이트
34
+ result . push ( [ start , end ] ) ;
35
+ [ start , end ] = [ newStart , newEnd ] ;
36
+ }
37
+ }
38
+
39
+ // 마지막 구간 추가
40
+ result . push ( [ start , end ] ) ;
41
+
42
+ return result ;
43
+ }
You can’t perform that action at this time.
0 commit comments