forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYjason-K.ts
More file actions
41 lines (37 loc) ยท 1.45 KB
/
Yjason-K.ts
File metadata and controls
41 lines (37 loc) ยท 1.45 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
38
39
40
/**
* ์๋ก์ด interval์ ๊ธฐ์กด intervals ๋ฐฐ์ด์ ์ฝ์
ํ๊ณ ๊ฒน์น๋ ๊ตฌ๊ฐ์ ๋ณํฉํ์ฌ ๋ฐํํ๋ ํจ์
* @param {number[][]} intervals - ๊ธฐ์กด interval ๋ฐฐ์ด
* @param {number[]} newInterval - ์ถ๊ฐํ๋ ค๋ interval
* @returns {number[][]} - ์๋ก์ด interval์ ์ถ๊ฐํ๊ณ ๋ณํฉํ ๋ฐฐ์ด
*
* ์๊ฐ๋ณต์ก๋ : O(n)
* - intervals ๋ฐฐ์ด์ ์ํํ๋ฉด์ newInterval๊ณผ ๊ฒน์น๋ ๊ตฌ๊ฐ์ ์ฐพ์ ๋ณํฉ
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(n)
* - ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ๋ฐฐ์ด์ ์์ฑ.
*/
function insert(intervals: number[][], newInterval: number[]): number[][] {
// ๊ฒฐ๊ณผ ๋ฐฐ์ด์ newInterval ํ๋๋ง ๊ฐ์ง ๋ฐฐ์ด๋ก ์์
const result: number[][] = [newInterval];
for (let i = 0; i < intervals.length; i++) {
const newItem = intervals[i];
const lastItem = result.pop()!;
// ํ์ฌ ๊ตฌ๊ฐ์ด lastItem ๊ตฌ๊ฐ์ ์ผ์ชฝ์ ์์ ํ ์์นํ๋ ๊ฒฝ์ฐ
if (newItem[1] < lastItem[0]) {
result.push(newItem);
result.push(lastItem);
}
// ํ์ฌ ๊ตฌ๊ฐ์ด lastItem ๊ตฌ๊ฐ์ ์ค๋ฅธ์ชฝ์ ์์ ํ ์์นํ๋ ๊ฒฝ์ฐ
else if (newItem[0] > lastItem[1]) {
result.push(lastItem);
result.push(newItem);
}
// ๋ ๊ตฌ๊ฐ์ด ๊ฒน์น๋ ๊ฒฝ์ฐ: ๋ณํฉํ์ฌ ํ๋์ ๊ตฌ๊ฐ์ผ๋ก ๋ณํฉ
else {
lastItem[0] = Math.min(lastItem[0], newItem[0]);
lastItem[1] = Math.max(lastItem[1], newItem[1]);
result.push(lastItem);
}
}
return result;
}