๋ฐ์ํ
K๋ฒ์งธ์
๋ฐฐ์ด array์ i๋ฒ์งธ ์ซ์๋ถํฐ j๋ฒ์งธ ์ซ์๊น์ง ์๋ฅด๊ณ ์ ๋ ฌํ์ ๋, k๋ฒ์งธ์ ์๋ ์๋ฅผ ๊ตฌํ๋ ค ํฉ๋๋ค. ์๋ฅผ ๋ค์ด array๊ฐ [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3์ด๋ผ๋ฉด
1. rray์ 2๋ฒ์งธ๋ถํฐ 5๋ฒ์งธ๊น์ง ์๋ฅด๋ฉด [5, 2, 6, 3]์
๋๋ค.
2. 1์์ ๋์จ ๋ฐฐ์ด์ ์ ๋ ฌํ๋ฉด [2, 3, 5, 6]์
๋๋ค.
3. 2์์ ๋์จ ๋ฐฐ์ด์ 3๋ฒ์งธ ์ซ์๋ 5์
๋๋ค.
๋ฐฐ์ด array, [i, j, k]๋ฅผ ์์๋ก ๊ฐ์ง 2์ฐจ์ ๋ฐฐ์ด commands๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, commands์ ๋ชจ๋ ์์์ ๋ํด ์์ ์ค๋ช
ํ ์ฐ์ฐ์ ์ ์ฉํ์ ๋ ๋์จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์ด์ ๋ด์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์กฐ๊ฑด
* array์ ๊ธธ์ด๋ 1 ์ด์ 100 ์ดํ์
๋๋ค.
* array์ ๊ฐ ์์๋ 1 ์ด์ 100 ์ดํ์ ๋๋ค.
* commands์ ๊ธธ์ด๋ 1 ์ด์ 50 ์ดํ์ ๋๋ค.
* commands์ ๊ฐ ์์๋ ๊ธธ์ด๊ฐ 3์ ๋๋ค.
* array์ ๊ฐ ์์๋ 1 ์ด์ 100 ์ดํ์ ๋๋ค.
* commands์ ๊ธธ์ด๋ 1 ์ด์ 50 ์ดํ์ ๋๋ค.
* commands์ ๊ฐ ์์๋ ๊ธธ์ด๊ฐ 3์ ๋๋ค.
๋ฌธ์ ํ์ด
answer, answer2 ๋ ๊ฐ์ ๋ฐฐ์ด์ ์์ฑํ ๋ค์ for๋ฌธ์ ์ด์ฉํ์ฌ answer ์์ ํด๋นํ๋ ๊ฐ์ ์
๋ ฅํ๋ค. ์ดํ, sort()๋ก ์ ๋ ฌํ๊ณ ์ ๋ ฌํ ๊ฐ์์ ๋ค์ ํด๋นํ๋ ๊ฐ์ ์ถ์ถํ์ฌ ์๋ก์ด ๋ฐฐ์ด answer2์ ์ ์ฅ์ํจ๋ค. answer2์ ํํ๋ [[์ซ์], [์ซ์], [์ซ์], ...]์ด๊ธฐ ๋๋ฌธ์, map์ ์ฌ์ฉํด ํ๋์ ๋ฐฐ์ด๋ก ๋ง๋ค์ด์ฃผ์๋ค.
function solution(array, commands) {
let answer = [];
let answer2 = [];
for(i=0; i<commands.length; i++){
answer.push(array.slice(commands[i][0] - 1, commands[i][1]));
answer[i].sort(function(a,b){return a-b});
answer2.push(answer[i].slice(commands[i][2] - 1, commands[i][2]));
}
return answer2.map(el => Number(el));
}
๋ค๋ฅธ ํ์ด ๋ฐฉ์
function solution(array, commands) {
return commands.map(v => {
return array.slice(v[0] - 1, v[1]).sort((a, b) => a - b).slice(v[2] - 1, v[2])[0];
});
}
๋ฐ์ํ
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm] ํ๋ก๊ทธ๋๋จธ์ค Lv.1 : ์์ฐ (1) | 2022.11.28 |
---|---|
[Algorithm] ํ๋ก๊ทธ๋๋จธ์ค Lv.1 : 3์ง๋ฒ ๋ค์ง๊ธฐ (1) | 2022.11.28 |
[Algorithm] ํ๋ก๊ทธ๋๋จธ์ค Lv.1 : ์ฝ์์ ๊ฐ์์ ๋ง์ (1) | 2022.11.25 |
[Algorithm] ํ๋ก๊ทธ๋๋จธ์ค Lv.1 : ์์ ๋ํ๊ธฐ (1) | 2022.11.22 |
[Algorithm] ํ๋ก๊ทธ๋๋จธ์ค Lv.1 : ๋ฌธ์์ด ๋ด๋ฆผ์ฐจ์์ผ๋ก ๋ฐฐ์นํ๊ธฐ (2) | 2022.11.21 |
๋๊ธ