코딩테스트 연습 29: [프로그래머스] K번째수

gyomni·2022년 1월 26일
0

Algorithm

목록 보기
29/33
post-thumbnail

출처 : 프로그래머스
사용 언어 : JavaScript

초기 코드

function solution(array, commands) {
    var answer = [];
    return answer;
}

내가 작성한 코드

function solution(array, commands) {
    var answer = [];
    let arr=[];
    for(let i=0;i<commands.length;i++){
        let num1=commands[i][0];
        let num2=commands[i][1];
        let num3=commands[i][2];
        
        arr = array.slice(num1-1,num2);
        arr.sort((a,b)=>a-b);
        answer.push(arr[num3-1]);
    }
    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]
    })
}

🙍‍♀️ 📝

배열 디스트럭처링 할당 -> const [sPosition, ePosition, position] = command
filter, map은 원본 배열을 훼손하지 않고 새로운 배열을 만들어서 리턴!

profile
Front-end developer 👩‍💻✍

0개의 댓글