개발_자 2024. 7. 12. 12:19

 

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

 

`slice(start, end)`

start에서 end값 까지 추출

 

배열의 인덱스는 0부터 시작하기 때문에

명령에서 주어진 인덱스를 실제 배열의 인덱스로 변환할 때 1을 뺌

 

`sort((a,b) => a - b)`

오름차순 정렬

 

 

 


 

 

 

다른 사람 풀이

function solution(array, commands) {
    return commands.map(command => {
        // command 배열의 요소를 각각 변수로 할당
        const [sPosition, ePosition, position] = command;
        
        // array에서 sPosition과 ePosition 사이의 부분 배열을 추출하고 정렬
        const newArray = array
            .filter((value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1)
            .sort((a, b) => a - b);
        
        // 추출된 부분 배열에서 position번째 요소를 반환
        return newArray[position - 1];
    });
}

 

 

`map()`

`commands` 배열의 각 요소에 대해 주어진 함수를 호출,

그 결과를 새로운 배열로 반환

 

`command`는 `commands` 배열의 각 요소

 

명령 배열 `command`는

`[sPosition, ePosition, position]` 형태의 세 개의 숫자 가짐

배열 비구조화 할당을 사용하여

각각 시작 위치, 끝 위치, 목표 위치로 나눔

 

`filter` 메서드를 사용하여

주어진 시작 위치 (sPosition - 1)와 끝 위치 (ePosition - 1) 사이의 요소만을 추출

`fIndex`는 배열 요소의 인덱스

 

`fIndex >= sPosition - 1 && fIndex <= ePosition - 1`

조건을 만족하는 요소만을 새로운 배열로 만듦

 

추출된 부분 배열을 `sort` 메서드를 사용하여 오름차순으로 정렬

 

정렬된 배열 `newArray`에서 `position - 1` 번째 요소를 선택하여 반환