1
1
---
2
2
layout : post
3
- title : (Leetcode) 57 - Insert Interval
3
+ title : (Leetcode) 57 - Insert Interval 풀이
4
4
categories : [스터디-알고리즘]
5
5
tags :
6
6
[
13
13
array,
14
14
typing,
15
15
list,
16
+ java,
17
+ Java,
18
+ merge,
19
+ copy,
16
20
]
17
21
date : 2024-02-14 20:30:00 +0900
18
22
---
@@ -31,6 +35,8 @@ date: 2024-02-14 20:30:00 +0900
31
35
32
36
---
33
37
38
+ ## 내가 작성한 풀이
39
+
34
40
``` python
35
41
from typing import List
36
42
@@ -63,7 +69,7 @@ class Solution:
63
69
return intervals[0 :startIndex] + [newNode] + intervals[endIndex + 1 : len (intervals)]
64
70
```
65
71
66
- ## 파이썬 테스트 코드 작성
72
+ ### 파이썬 테스트 코드 작성
67
73
68
74
이번부터는 테스트 코드도 작성해봐야겠다 싶어서 찾아보니 python에서는 기본적으로 assert라는 간단한 검증 구문을 기능으로 제공하고 있었다.
69
75
@@ -104,10 +110,111 @@ AssertionError
104
110
105
111
expected를 보여주는것은 좋지만 그와 함께 실제로는 어떤 결과가 나왔는지도 보여줬다면 더 좋지 않을까 싶긴하다.
106
112
107
- ## 궁금한 점
113
+ ### 궁금한 점
108
114
109
115
``` python
110
116
from typing import List
111
117
```
112
118
113
119
코딩테스트 같은걸 할 때 라이브러리를 추가하지 못하게 하는걸로 알고 있는데 typing에 있는 List는 써도 되는건가 싶긴하다. 나중에 잘 아는 사람이 있다면 물어봐야겠다.
120
+
121
+ -> 써도 됨.
122
+
123
+ ## 자바로 다시 풀기 (24.07.23)
124
+
125
+ ### Merge Intervals 문제 답안 응용하기
126
+
127
+ 바로 전에 풀었던 [ Merge Intervals] ( https://algorithm.jonghoonpark.com/2024/07/23/leetcode-56 ) 를 그대로 가져다 쓸 수 있을 것 같아서 해보았더니 통과 된다.
128
+
129
+ ``` java
130
+ public int [][] insert(int [][] intervals, int [] newInterval) {
131
+ int [][] newIntervals = Arrays . copyOf(intervals, intervals. length + 1 );
132
+ newIntervals[intervals. length] = newInterval;
133
+ return merge(newIntervals);
134
+ }
135
+
136
+ public int [][] merge(int [][] intervals) {
137
+ Arrays . sort(intervals, Comparator . comparingInt(o - > o[0 ]));
138
+
139
+ Deque<int[]> intervalDeque = new ArrayDeque<> ();
140
+ intervalDeque. add(intervals[0 ]);
141
+ for (int i = 1 ; i < intervals. length; i++ ) {
142
+ int [] lastElement = intervalDeque. getLast();
143
+ int [] nextElement = intervals[i];
144
+
145
+ if (lastElement[1 ] >= nextElement[0 ]) {
146
+ int [] mergedElement = new int []{
147
+ lastElement[0 ],
148
+ Math . max(lastElement[1 ], nextElement[1 ])
149
+ };
150
+ intervalDeque. removeLast();
151
+ intervalDeque. add(mergedElement);
152
+ } else {
153
+ intervalDeque. add(nextElement);
154
+ }
155
+ }
156
+
157
+ return intervalDeque. toArray(int [][]:: new );
158
+ }
159
+ ```
160
+
161
+ #### TC , SC
162
+
163
+ 시간 복잡도는 `O(n* logn)` 공간 복잡도는 `O(n)` 이다. (결과를 반환하기 위해 생성된 `int [][]`는 고려하지 않는다. )
164
+
165
+ ### 성능을 개선한 답안 (pointer 사용)
166
+
167
+ 문제를 잘 읽어보면 intervals 의 경우 start를 기준으로 이미 정렬이 되어있다고 하였기 떄문에 따로 정렬을 해줄 필요는 없다.
168
+ for loop 에서는 start, end pointer를 이용해서 어느 구간이 병합되는지 기억해두고, 최종적으로 병합을 진행한다.
169
+
170
+ `System . arraycopy` 의 경우에는 ([공식 문서](https: // docs.oracle.com/javase/8/docs/api/java/lang/System.html#arraycopy-java.lang.Object-int-java.lang.Object-int-int-)) array의 data를 copy할 때 효율적으로 처리할 수 있지만, api가 직관적이지는 못한 것 같다. 그래도 한 번 적용해보았다.
171
+
172
+ ```java
173
+ class Solution {
174
+ public int [][] insert (int [][] intervals , int [] newInterval ) {
175
+ int start = - 1 ;
176
+ int end = - 1 ;
177
+
178
+ for (int i = 0 ; i < intervals. length; i++ ) {
179
+ if (start == - 1 && intervals[i][1 ] >= newInterval[0 ]) {
180
+ start = i;
181
+ }
182
+
183
+ if (newInterval[1 ] >= intervals[i][0 ]) {
184
+ end = i;
185
+ }
186
+ }
187
+
188
+ if (start == - 1 ) {
189
+ int [][] newIntervals = Arrays . copyOf(intervals, intervals. length + 1 );
190
+ newIntervals[intervals. length] = newInterval;
191
+ return newIntervals;
192
+ }
193
+
194
+ if (end == - 1 ) {
195
+ int [][] newIntervals = new int [intervals. length + 1 ][2 ];
196
+ newIntervals[0 ] = newInterval;
197
+ System . arraycopy(intervals, 0 , newIntervals, 1 , newIntervals. length - 1 );
198
+ return newIntervals;
199
+ }
200
+
201
+ int [][] newIntervals = new int [intervals. length - (end - start)][2 ];
202
+
203
+ if (start >= 0 ) {
204
+ System . arraycopy(intervals, 0 , newIntervals, 0 , start);
205
+ }
206
+
207
+ newIntervals[start] = new int []{Math . min(intervals[start][0 ], newInterval[0 ]), Math . max(intervals[end][1 ], newInterval[1 ])};
208
+
209
+ if (intervals. length - (end + 1 ) >= 0 ) {
210
+ System . arraycopy(intervals, end + 1 , newIntervals, end + 1 - (end - start), intervals. length - (end + 1 ));
211
+ }
212
+
213
+ return newIntervals;
214
+ }
215
+ }
216
+ ```
217
+
218
+ #### TC , SC
219
+
220
+ 시간 복잡도는 `O(n)` 공간 복잡도는 `O(1 )` 이다. (결과를 반환하기 위해 생성된 `int [][]`는 고려하지 않는다. )
0 commit comments