본문 바로가기
Research/Coding Test

정렬_K번째수

by RIEM 2023. 11. 18.

나의 해결 방법

function solution(array, commands) {
    const result = [];
    
    commands.forEach(el => {
        const [i, j, k] = el
        const cutArr = array.slice(i-1, j).sort((a, b) => a - b);
        result.push(cutArr[k-1])
    })
    return result;
}

이건 쉬운 문제.

 

타인의 해결 방법

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]
    })
}

2차원 배열인 commands을 map 루프 돌면서, 해당 배열을 3개 변수로 분해해주는 점은 비슷하고 그 외에도 거의 비슷하다.

다만, filter의 idx 기준으로 배열을 자른 점이 흥미로운 접근이라 생각했다. 하지만 filter로 할 필요가 있는지는 의문이다. slice 메소드가 명시적으로 자른다는 의미에서 더 적절하다고 생각한다. 

'Research > Coding Test' 카테고리의 다른 글

스택/큐_기능개발  (1) 2023.11.19
스택/큐_같은 숫자는 싫어  (1) 2023.11.19
해시_전화번호 목록  (0) 2023.11.18
해시_폰켓몬  (0) 2023.11.17
프로그래머스_lv0_안전지대  (0) 2023.11.17

댓글