[Snow-ball]프로그래밍(컴퓨터)/Algorithm Training
[Algorithm] K번째수 (JavaScript - Programmers)
Snow-ball
2023. 6. 3. 22:46
반응형
문제 설명
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
1. array의 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 함수를 작성해주세요.
입출력 예

1차 답안 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
const solution = (array, commands) => {
const answer = [];
commands.map((el, key) => {
const arr = [];
for (let i = el[0] - 1; i < el[1]; ++i) {
arr.push(array[i]);
}
arr.sort((a, b) => a - b);
answer.push(arr[el[2] - 1]);
});
return answer;
};
solution(
[1, 5, 2, 6, 3, 7, 4],
[
[2, 5, 3],
[4, 4, 1],
[1, 7, 3],
]
);
|
cs |
2차 답안 코드
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
|
const solution = (array, commands) => {
const answer = [];
commands.map((command) => {
const [start, end, pivot] = command;
answer.push(
array
.filter((el, key) => key >= start - 1 && key <= end - 1)
.sort((a, b) => a - b)[pivot - 1]
);
});
return answer;
};
console.log(
solution(
[1, 5, 2, 6, 3, 7, 4],
[
[2, 5, 3],
[4, 4, 1],
[1, 7, 3],
]
)
);
|
cs |
3차 답안 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
const solution = (array, commands) => {
return commands.map((command) => {
const [start, end, pivot] = command;
return array
.filter((el, key) => key >= start - 1 && key <= end - 1)
.sort((a, b) => a - b)[pivot - 1];
});
};
console.log(
solution(
[1, 5, 2, 6, 3, 7, 4],
[
[2, 5, 3],
[4, 4, 1],
[1, 7, 3],
]
)
);
|
cs |
4차 답안 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
const solution = (array, commands) => {
return commands.map(
(command) =>
array
.slice(command[0] - 1, command[1])
.sort((a, b) => a - b)
.slice(command[2] - 1, command[2])[0]
);
};
console.log(
solution(
[1, 5, 2, 6, 3, 7, 4],
[
[2, 5, 3],
[4, 4, 1],
[1, 7, 3],
]
)
);
|
cs |
5차 답안 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
const solution = (array, commands) => {
return commands.map(
(command) =>
array.slice(command[0] - 1, command[1]).sort((a, b) => a - b)[
command[2] - 1
]
);
};
console.log(
solution(
[1, 5, 2, 6, 3, 7, 4],
[
[2, 5, 3],
[4, 4, 1],
[1, 7, 3],
]
)
);
|
cs |
반응형