forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimsosleepy.java
More file actions
37 lines (31 loc) ยท 1.4 KB
/
imsosleepy.java
File metadata and controls
37 lines (31 loc) ยท 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// start์ end๋ผ๋ ๋๊ฐ์ ๋ณ์๋ฅผ ์ด์ฉํ๋ฉด ํ๋ฒ๋ง ์ํํด๋ ๊ฐ๋ฅํ๋ค.
// ์กฐ๊ฑด์ด ์ธ๊ฐ ๋ฐ์ ์์ด์ ๋จ์ํ๊ฒ ์๋ฎฌ๋ ์ด์
ํ๋ฉด๋๋ค.
// (1) ํ์ฌ ๊ตฌ๊ฐ์ด newInterval๋ณด๋ค ์์ ์์ โ ๊ทธ๋๋ก ์ถ๊ฐ
// (2) ํ์ฌ ๊ตฌ๊ฐ์ด newInterval๋ณด๋ค ๋ค์ ์์ โ ๋ณํฉํ ํ์ ์์, ๋ฐ๋ก ์ถ๊ฐ
// (3) ๊ฒน์น๋ ๊ฒฝ์ฐ ๋ณํฉ
// ๋ง์ง๋ง newInterval ์ถ๊ฐ (๋ณํฉ๋ ์ํ์ผ ์๋ ์์) << ์ด๊ฑธ ๋ชป์ฐพ์์ ๋๋ฌด ์ค๋๊ฑธ๋ฆผ
// ์๊ฐ๋ณต์ก๋ O(N)
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> result = new ArrayList<>();
int n = intervals.length;
int start = newInterval[0];
int end = newInterval[1];
for (int i = 0; i < n; i++) {
if (intervals[i][1] < start) {
result.add(intervals[i]);
}
else if (intervals[i][0] > end) {
result.add(new int[]{start, end});
start = intervals[i][0]; // ๊ธฐ์กด ๊ตฌ๊ฐ๋ถํฐ ๋ค์ ์ถ๊ฐ
end = intervals[i][1];
}
else {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
}
}
result.add(new int[]{start, end});
return result.toArray(new int[result.size()][]);
}
}