File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -41,3 +41,34 @@ function merge(intervals: number[][]): number[][] {
4141
4242 return result ;
4343}
44+
45+ /**
46+ * 접근 방법 :
47+ * - O(n)시간복잡도로 풀기 위해서 정렬하지 않고 intervals 병합
48+ * - 겹치지 않는 구간은 그대로 저장(left, right)
49+ * - newInterval과 겹치는 구간은 병합하여 하나의 interval로 대체
50+ *
51+ * 시간복잡도 : O(n)
52+ * - n = 인터벌 배열의 길이
53+ * - 1회 순회하면서 병합하므로 O(n)
54+ *
55+ * 공간복잡도 : O(n)
56+ * - 결과 배열에 담아서 리턴
57+ */
58+ function insert ( intervals : number [ ] [ ] , newInterval : number [ ] ) : number [ ] [ ] {
59+ const left : number [ ] [ ] = [ ] ;
60+ const right : number [ ] [ ] = [ ] ;
61+
62+ for ( const [ start , end ] of intervals ) {
63+ if ( end < newInterval [ 0 ] ) {
64+ left . push ( [ start , end ] ) ;
65+ } else if ( newInterval [ 1 ] < start ) {
66+ right . push ( [ start , end ] ) ;
67+ } else {
68+ newInterval [ 0 ] = Math . min ( newInterval [ 0 ] , start ) ;
69+ newInterval [ 1 ] = Math . max ( newInterval [ 1 ] , end ) ;
70+ }
71+ }
72+
73+ return [ ...left , newInterval , ...right ] ;
74+ }
You can’t perform that action at this time.
0 commit comments