문제 링크: 정렬 > k번째 수
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
array | commands | return |
---|---|---|
[1, 5, 2, 6, 3, 7, 4] | [[2, 5, 3], [4, 4, 1], [1, 7, 3]] | [5, 6, 3] |
function solution(array, commands) {
var answer = [];
for (let a in commands) {
let i = commands[a][0] - 1,
j = commands[a][1],
k = commands[a][2] - 1;
let slice = array.slice(i, j).sort((a, b) => a - b);
answer.push(slice[k]);
}
return answer;
}
function solution(array, commands) {
return commands.map(command => {
const [sPosition, ePosition, position] = command
const newArray = array
.filter((value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1)
.sort((a,b) => a - b)
return newArray[position - 1]
})
}
commands의 요소들을 다 따로 정의하지 않고 const [sPosition, ePosition, position] = command로 정의 이 부분 왜 생각을 못했을까ㅠ