본문 바로가기
ALGORITHM/프로그래머스 With JS

[프로그래머스] K번째수 / Javascript

by LAY CODER 2021. 4. 27.

문제

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 


 

TRY 1

let array = [1, 5, 2, 6, 3, 7, 4];
let commands = [
    [2, 5, 3],
    [4, 4, 1],
    [1, 7, 3],
];

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

    for (let i = 0; i < commands.length; i++) {
        answer.push(
            array
                .slice(commands[i][0] - 1, commands[i][1])
                .sort((a, b) => a - b)[commands[i][2] - 1],
        );
    }

    return answer;
}

console.log(solution(array, commands));

 

start에서 end까지 자른다는 구문을 봤을 때 바로 Array.slice()를 이용해야 한다고 생각했다.

 

2번째 숫자부터 라는 말은 1번 인덱스부터 시작한다는 말이고

 

5번째 숫자까지는 4번 인덱스(= 5번 인덱스 미만)까지 자른다는 걸 유의해야 한다.

 

그 다음, Array.sort()를 이용하여 오름차순으로 정렬하고

 

3번째 숫자(2번 인덱스)를 정답 배열에 Array.push() 하면 된다.

 


 

TRY 2 

let array = [1, 5, 2, 6, 3, 7, 4];
let commands = [
    [2, 5, 3],
    [4, 4, 1],
    [1, 7, 3],
];

function solution(array, commands) {
    return commands.map((command) => {
    
        // commands의 요소들을 명시적으로 구조 분해 할당
        const [sPoint, ePoint, point] = command;
        
        // array에서 인덱스 가 스타팅포인트 - 1(2번째부터 시작하려면 1번인덱스이기 때문) 이상
        // 엔드포인트 - 1(5번째면 4번 인덱스) 이하 까지 추출해서 newArray에 넣어준다.
        // sort를 이용하여 오름차순으로 정렬
        const newArray = array
            .filter(
                (value, fIndex) => fIndex >= sPoint - 1 && fIndex <= ePoint - 1,
            )
            .sort((a, b) => a - b);

        // 포인트 - 1 번째(3번째면 2번 인덱스) 요소를 answer에 return
        return newArray[point - 1];
    });
}

console.log(solution(array, commands));

 

Array map()을 이용해서 for문을 이용하지 않고 더 간단하게 표현 할 수 있다.

 

commands 각 배열의 요소들을 [sPoint(시작점), ePoint(끝점), point(k번째 수)] 배열에 구조 분해 할당하였고

 

Array.filter()를 이용하여 array를 해당 조건에 맞게 필터링해주고 오름차순 정렬하여 새로운 배열에 넣어준다.

 

그 뒤에 새로운 배열에 k 번째수를 반환하여 commands 배열을 재구성하는 방법이다.

 


 

BEST

let array = [1, 5, 2, 6, 3, 7, 4];
let commands = [
    [2, 5, 3],
    [4, 4, 1],
    [1, 7, 3],
];

function solution(array, commands) {
    return commands.map(
        ([from, to, k]) =>
            array.slice(from - 1, to).sort((a, b) => a - b)[k - 1],
    );
}

console.log(solution(array, commands));

 

2번째 방법을 좀 더 간결하게 작성한 방법이다.

 

commands 각 배열의 요소들을 map의 from(시작), to(끝), k(k번째 수) 인자로 주면서 명시적으로 표현했고

 

array를 from, to 조건에 맞게 자르고 정렬한 뒤에 k번째 수를 구하여

 

commands 배열을 재구성한 뒤에 반환하는 방법이다.

댓글