프로그래머스 코딩테스트 - K 번째 수

프로그래머스 - K번째 수

내 풀이

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

  commands.forEach((item, index) => {
    let arr = array.map((item) => item);

    let middleNumber = arr
      .splice(item[0] - 1, item[1] - item[0] + 1)
      .sort((a, b) => a - b)[item[2] - 1];

    answer.push(middleNumber);
  });

  return answer;
}

sort() 는 아스키코드값으로 정렬하기 때문에 내림차순과 올림차순을 정확하게 명시해줘야한다. 이것 때문에 테스트케이스 2번이 통과가 안돼 좀 해맸다.

다른 사람 풀이

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];
  });
}
  • forEach로 순회하지 않고 map 을 이용해 바로 배열을 생성해 리턴할 수 있다. 그리고 filter의 index 값을 이용해 배열을 정리해버리는 것도,
  • splice를 하면 원본 배열이 변형되기 때문에 map을 통해 배열을 복사해 복사한 배열로 splice를 수행했는데 이 방법은 그럴 필요없이 깔끔하게 할 수 있다.