[알고리즘] K번째 수 - JS

Yoon·2021년 8월 1일
0

프로그래머스 Lv1.

목록 보기
8/19
post-thumbnail

문제

Solution

  • 나의 풀이
function solution(arr, commands) {
    let answer=[];
    
    for(let x of commands){
        let t = [];
        for(let i=x[0]-1;i<x[1];i++){
            t.push(arr[i]);
        }
        t = t.sort((a,b)=>a-b);
        answer.push(t[x[2]-1]);
    }
    
    return answer;
}
  • 다른풀이1
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
구조 분해 할당을 써서 표현할 수도 있다.

  • 다른풀이2
function solution(array, commands) {
    return commands.map(v => {
        return array.slice(v[0] - 1, v[1]).sort((a, b) => a - b).slice(v[2] - 1, v[2])[0];
    });
}

slice함수를 이용

profile
FE Developer✨

0개의 댓글