개발일지

프로그래머스 - K번째수 (JavaScript, JS) 본문

개발일지/알고리즘

프로그래머스 - K번째수 (JavaScript, JS)

Seobe95 2021. 8. 5. 01:05

생각한 점

1. commands 안의 배열의 첫번째 수 부터 두번째 수까지 빈 배열에 push

2. 이후 오름차순으로 정렬

3. 세번째 수의 순서의 숫자를 구하기


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

이후, 다른 사람들의 풀이 방법을 보고 slice함수를 사용해서 푼 것을 보고,  이걸 사용해도 되었겠다 싶었다.

function solution(array, commands) {
  var answer = [];
  var count = 0;
  while (count < commands.length) {
    let temp = [];
    let one = commands[count][0];
    let two = commands[count][1];
    let thr = commands[count][2];
    let sliceArr = array.slice(one - 1, two);
    sliceArr.sort((a, b) => a - b);
    answer.push(sliceArr[thr-1]);
    count ++;
  }
  return answer;
}