File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ *@link https://leetcode.com/problems/insert-interval/description/
3
+ *
4
+ * 접근 방법 :
5
+ * - 새로운 interval을 기존 interval에 추가하고, 시작 지점 기준으로 오름차순 정렬
6
+ * - 현재 interval이 result의 마지막 interval과 겹치는 경우, 종료 지점 업데이트해서 병함
7
+ * - 겹치지 않으면, result 배열에 현재 interval 추가
8
+ *
9
+ * 시간복잡도 : O(nlogn)
10
+ * - n = intervals 개수
11
+ * - 오름차순으로 정렬
12
+ *
13
+ * 공간복잡도 : O(n)
14
+ * - n = 병합 후 result 배열에 담긴 인터벌의 개수
15
+ */
16
+ function insert ( intervals : number [ ] [ ] , newInterval : number [ ] ) : number [ ] [ ] {
17
+ const sortedIntervals = [ ...intervals , newInterval ] . sort (
18
+ ( a , b ) => a [ 0 ] - b [ 0 ]
19
+ ) ;
20
+ const result : number [ ] [ ] = [ sortedIntervals [ 0 ] ] ;
21
+
22
+ for ( let i = 1 ; i < sortedIntervals . length ; i ++ ) {
23
+ const lastInterval = result [ result . length - 1 ] ;
24
+ const currentInterval = sortedIntervals [ i ] ;
25
+
26
+ if ( currentInterval [ 0 ] <= lastInterval [ 1 ] ) {
27
+ lastInterval [ 1 ] = Math . max ( currentInterval [ 1 ] , lastInterval [ 1 ] ) ;
28
+ } else {
29
+ result . push ( currentInterval ) ;
30
+ }
31
+ }
32
+
33
+ return result ;
34
+ }
You can’t perform that action at this time.
0 commit comments