문제

 

풀이 코드

function solution(array, commands) {
  let arr = [];

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

 

풀이 과정

slice 메서드와 sort메서드를 이요해 비교적 쉽게 풀어낼수 있었다,

다만, 내가 풀면서도 가독성이 너무 떨어지는거 같았다.

 

하지만 다른 방법이 도저히 생각나지 않았다, 그래서 다른 사람의 풀이를 봤다.

 

다른사람의

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]
    })
}

구조분해 할당을 이용해 보다 직관적으로 분리하여 변수를 사용하셨다,

 

또한 slice가 아닌, filter를 이용하여 간단히 풀이하셨다.

 

가독성을 높이기 위해 기초적인 문법을 더 학습 해야 할거같다.

+ Recent posts