본문으로 건너뛰기
poylog

개발·AI

K번째 수

1분

https://programmers.co.kr/learn/courses/30/lessons/42748

배열의 범위를 주고, 범위 내에서 k번째 수를 구하는 문제다. 처음엔 splice() 메서드를 사용했지만, splice()는 원본 배열을 변경시키기 때문에 slice() 메서드를 이용해 풀었다.

sol 1

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

function solution(array,commands) {
  let answer = [];
  commands.forEach(v => {
    const arr = array.slice(v[0]-1,v[1]);
    arr.sort((a,b) => a-b);
    answer.push(arr[v[2]-1]);
  })
  return answer
}
console.log(solution(array,commands)) //[ 5, 6, 3 ]

For문보다는 forEach 메서드를 이용해 풀어보았다. forEach 메서드는 for 문에 비해 성능이 좋지는 않지만 가독성이 더 좋다고 한다. 시간이 많이 걸리는 복잡한 코드 또는 높은 성능이 필요한 경우가 아니라면 for 문 대신 forEach 메서드를 사용할 것을 권장한다. ( 출처 : deep dive)

sol 2

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


function solution(array, commands) {
  return commands.map(answer => {
    const [sPosition,ePosition,position] = answer
    const newArr = array
    .filter((v,i) => i>=sPosition-1 && i<=ePosition-1)
    .sort((a,b) => a-b)
    
    return newArr[position-1]
  })
}
console.log(solution(array,commands)) // [ 5, 6, 3 ]

구조분해할당으로 쪼개서 받은 후 filter 메서드를 이용해 범위를 지정한다. 배열 메서드를 잘 활용한 좋은 풀이인 것 같다.