January 22, 2021
배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
function solution(array, commands) {
var answer = []
return commands.map(res => {
let arr = []
let i = res[0] - 1
let k = res[1] - 1
// 시작인덱스와 종료인덱스를 파악하여, 내부의 값들만 담기
while (i <= k) {
arr.push(array[i])
i++
}
// 순서대로 정렬 후 반환
return arr.sort((a, b) => a - b)[res[2] - 1]
})
}
function solution(array, commands) {
return commands.map(command => {
const [sPosition, ePosition, position] = command
// commands순회를 돌려서, 시작인덱스 종료인덱스 파악 후, 숫자배열을 filter를 사용해 시작인덱스와 종료인덱스 사이인 인덱스를 갖고있는 값만 반환
const newArray = array
.filter(
(value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1
)
.sort((a, b) => a - b)
return newArray[position - 1]
})
}
// 원리는 내가 한것과 비슷하지만, 변수생성을 최소화하여 불필요한 공간을 줄인듯 하다.