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

woolee의 기록보관소·2022년 11월 8일
0

알고리즘 문제풀이

목록 보기
58/178

문제 출처

프로그래머스 lev1 - k번째 수

문제

나의 풀이

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

console.log(solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]]));

다른 풀이

구조분해할당

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]
    })
}
function solution(array, commands) {
    let answer = [];
    for(let i = 0; i < commands.length; i++){
      let eachCommand = commands[i]
      let slice = array.slice(eachCommand[0] - 1, eachCommand[1])
      answer.push(slice.sort((a, b) => a - b)[eachCommand[2] - 1])
    }

    return answer;
}
profile
https://medium.com/@wooleejaan

0개의 댓글