728x90
๋ฐ์ํ
๐ 09 - ๊ฒฐํผ์(๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ)
ํผ๋ก์ฐ ์ฅ์์ ๋์์ ์กด์ฌํ๋ ์ต๋ ์ธ์์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค. ํ ์น๊ตฌ๊ฐ ์ค๋ ์๊ฐ์ด 13, ๊ฐ๋ ์๊ฐ์ด 15๋ผ๋ฉด ์ด ์น๊ตฌ๋ 13์ ์ ๊ฐ์ ํผ๋ก์ฐ ์ฅ์ ์กด์ฌํ๋ ๊ฒ์ด๊ณ 15์ ์ ๊ฐ์๋ ์กด์ฌํ์ง ์๋๋ค๊ณ ๊ฐ์ ํ๋ค.
๋์ ํ์ด ๋ฐฉ๋ฒ
- ์ค๋ ์๊ฐ(s)๊ณผ ๊ฐ๋ ์๊ฐ(e)์ ๋๋์ด ๋ฐ๋ก ๋ฐฐ์ด์ ๋ง๋ ๋ค์ ์ค๋ฆ์ฐจ์ ์ ๋ ฌ์ ํ๋ค.
- ํฌ ํฌ์ธํฐ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ์ฌ p1์ด p2๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์ผ๋ฉด ์๋ก์ด ๋ฐฐ์ด์ ๊ฐ๋ ์๊ฐ(e)๋ฅผ ์ถ๊ฐํ๊ณ p2++์ ํ๋ค.
- p1์ด p2๋ณด๋ค ์๋ค๋ฉด ์ค๋ ์๊ฐ(s)๋ฅผ ์ถ๊ฐํ๊ณ p1++์ ํ๋ค.
- for ๋ฌธ์ ๋๋ฉด์ 's'๊ฐ ๋์ค๋ฉด cnt++์ ํด์ฃผ๊ณ 'e'๊ฐ ๋์ค๋ฉด cnt--๋ฅผ ํด์ค๋ค.
- ํผ๋ก์ฐ ์ฅ์์ ๋ค์ด์ค๊ฑฐ๋ ๋๊ฐ๋ ์ฌ๋์ด ๋ฐ์ํ ๋๋ง๋ค ํผ๋ก์ฐ ์ฅ์์ ์กด์ฌํ๋ ์ธ์์์ answer๋ฅผ ๋น๊ตํ์ฌ ๋ ํฐ ๊ฐ์ answer์ ์ ์ฅํ๋ค.
๐ ๊ฐ์ฌ๋ ํ์ด ๋ฐฉ๋ฒ
๋ฌธ์์ด์ ์์๋๋ก ๋น๊ตํ์ฌ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ๊ธฐ ์ํด ๋จ์ด ์ ๋ ฌ ๋ฌธ์ ์์ '>', '<' ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ๋ค. ๊ฐ์ฌ๋์ ํ์ด ๋ฐฉ๋ฒ์์๋ charCodeAt() ํจ์๋ฅผ ์ด์ฉํด ASCII ์ฝ๋๋ก ๋ฐ๊ฟ์ค ๋ค์ ์์๋๋ก ๋น๊ตํ๋ค.
- for ๋ฌธ์ ๋๋ฉด์ ํ ์น๊ตฌ์ ์ค๋ ์๊ฐ(s)๊ณผ ๊ฐ๋ ์๊ฐ(e)์ ๋๋์ด ๋ฐฐ์ด ํ์[์๊ฐ, 's' or 'e']์ผ๋ก ๋ฐฐ์ด์ ์ถ๊ฐํ๋ค.
- ์๊ฐ์ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ์ ํ๋๋ฐ ์ค๋ ์๊ฐ(s)๊ณผ ๊ฐ๋ ์๊ฐ(e)์ด ๋์ผํ๋ฉด ๋ฌธ์์ด์ ๋น๊ตํ์ฌ ์ ๋ ฌํ๋ค.
- for ๋ฌธ์ ๋๋ฉด์ 's'๊ฐ ๋์ค๋ฉด cnt++์ ํด์ฃผ๊ณ 'e'๊ฐ ๋์ค๋ฉด cnt--๋ฅผ ํด์ค๋ค.
- ํผ๋ก์ฐ ์ฅ์์ ๋ค์ด์ค๊ฑฐ๋ ๋๊ฐ๋ ์ฌ๋์ด ๋ฐ์ํ ๋๋ง๋ค ํผ๋ก์ฐ ์ฅ์์ ์กด์ฌํ๋ ์ธ์์์ answer๋ฅผ ๋น๊ตํ์ฌ ๋ ํฐ ๊ฐ์ answer์ ์ ์ฅํ๋ค.
๐ ํ์ด
// ๋์ ํ์ด ๋ฐฉ๋ฒ
function solution(times) {
let answer = Number.MIN_SAFE_INTEGER;
let s = times.map((time) => time[0]).sort((a, b) => a - b);
let e = times.map((time) => time[1]).sort((a, b) => a - b);
let se = [];
let p1 = (p2 = cnt = 0);
while (p1 < s.length && p2 < e.length) {
if (s[p1] === e[p2] || s[p1] > e[p2]) {
se.push('e');
p2++;
} else {
se.push('s');
p1++;
}
}
if (p1 === s.length) {
while (p2 < e.length) {
se.push('e');
p2++;
}
} else {
while (p1 < e.length) {
se.push('s');
p1++;
}
}
for (let x of se) {
if (x === 's') cnt++;
else cnt--;
answer = Math.max(answer, cnt);
}
return answer;
}
let arr = [
[14, 18],
[12, 15],
[15, 20],
[20, 30],
[5, 14],
];
console.log(solution(arr));
// ๊ฐ์ฌ๋ ํ์ด ๋ฐฉ๋ฒ
function solution(times) {
let answer = Number.MIN_SAFE_INTEGER;
let T_line = [];
for (let x of times) {
T_line.push([x[0], 's']);
T_line.push([x[1], 'e']);
}
T_line.sort((a, b) => {
if (a[0] === b[0]) return a[1].charCodeAt() - b[1].charCodeAt();
else return a[0] - b[0];
});
let cnt = 0;
for (let x of T_line) {
if (x[1] === 's') cnt++;
else cnt--;
answer = Math.max(answer, cnt);
}
return answer;
}
let arr = [
[14, 18],
[12, 15],
[15, 20],
[20, 30],
[5, 14],
];
console.log(solution(arr));
'Algorithm > ์ธํ๋ฐ(inflearn)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript/section 7] 11 - ๋ฎค์ง ๋น๋์ค (0) | 2022.10.10 |
---|---|
[JavaScript/section 7] 10 - ์ด๋ถ ๊ฒ์ (2) | 2022.10.09 |
[JavaScript/section 7] 08 - ํ์์ค ๋ฐฐ์ (0) | 2022.10.07 |
[JavaScript/section 7] 07 - ์ขํ ์ ๋ ฌ (0) | 2022.10.06 |
[JavaScript/section 7] 06 - ์ฅ๋๊พธ๋ฌ๊ธฐ ํ์ (0) | 2022.10.06 |