🕊 Link

Lv1. K번째수 Javascript
https://programmers.co.kr/learn/courses/30/lessons/42748

🧑🏻‍💻 Code(javascript)

function solution(array, cmds) {
  const answer = [];
  cmds.forEach((item) => {
    const clone = array.slice();
    const edit = clone
      .splice(item[0] - 1, item[1] - item[0] + 1)
      .sort((a, b) => a - b);
    answer.push(edit[item[2] - 1]);
  });
  return answer;
}

💡 Solution

function solution(array, cmds) {
  const answer = [];
  cmds.forEach((item) => {
    // 원본을 수정하지 않는 slice 함수 활용
    const clone = array.slice();
    // cmds를 돌면서 배열안의 배열에서 index를 뽑아 사용
    const edit = clone
      .splice(item[0] - 1, item[1] - item[0] + 1)
      .sort((a, b) => a - b);
    answer.push(edit[item[2] - 1]);
  });
  return answer;
}

👨🏻‍💻💭 Self Feedback

map, slice, array clone
멋진 programmers 다른 사람의 풀이

function solution(array, commands) {
  return commands.map(
    ([from, to, k]) => array.slice(from - 1, to).sort((x, y) => x - y)[k - 1]
  );
}

  • 2021.04.16 - 최초 작성

댓글 환영 질문 환영
by.protect-me

profile
protect me from what i want

0개의 댓글