K번째 수

Happhee·2022년 2월 16일

[ LV1 ]  programmers

목록 보기
4/4
post-thumbnail

📝 K번째 수

🖥 나의 JS 코드

1️⃣ 첫번째 시도

function solution(array, commands) {
    var start, end , choice;
    
    commands.map((command)=> {
        start =command[0];
        end = command[1];
        choice = command[2]
    
        answer.push(array.slice(start-1, end).sort((a,b)=>a-b)[choice-1]);
    })
    
    return answer;
}

2️⃣ 두번째 시도

const의 변수를 사용하여 변하지 않는 값으로 명시하여 필요없는 스코프를 삭제하였다
더 간결하고 짧은 코드로 구현!

function solution(array, commands) {
    let answer = [];
    for(const command of commands){
        let commandArray = array.slice(command[0]-1, command[1]);
        commandArray.sort((a,b)=> a- b);
        answer.push(commandArray[command[2]-1])
    }
    return answer;
}
profile
즐기면서 정확하게 나아가는 웹프론트엔드 개발자 https://happhee-dev.tistory.com/ 로 이전하였습니다

0개의 댓글